C++ 虚函数几个实例

C++中的虚函数

虚函数必须被实现,如果不希望被实现,必须在父类中声明为0;

#include<iostream>
using namespace std;
class Virtualbase
{
public:
	virtual void Demon() = 0;
	virtual void Base() = 0;
	// virtual void Base() { cout << "this is farther class" << endl; }
};

class SubVirtual :public Virtualbase
{
public:
	void Demon()
	{
		cout << "this is SubVirtual!" << endl;
	}
	void Base()
	{
	cout << "this is subclass Base!" << endl;
	}

};

int main()
{
	Virtualbase* inst = new SubVirtual();
	inst->Base();
	inst->Demon();
	
	char c;
	cin >> c;
	return 0;
}

/*
输出:

this is subclass Base!
this is SubVirtual!
*/

非虚函数

#include<iostream>
using namespace std;
class Virtualbase
{
public:
	virtual void Demon() = 0;
	void Base() { cout << "This is farther class" << endl;  }
	// virtual void Base() = 0;
	// virtual void Base() { cout << "this is farther class" << endl; }
};

class SubVirtual :public Virtualbase
{
public:
	void Demon()
	{
		cout << "this is SubVirtual!\n" << endl;
	}
	void Base()
	{
	cout << "this is subclass Base\n" << endl;
	}

};

int main()
{
	Virtualbase* inst = new SubVirtual();
	inst->Base();
	inst->Demon();
	
	char c;
	cin >> c;
	return 0;
}

/*
输出

This is farther class
this is SubVirtual!
*/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部