c ++ pure virtual functions of the abstract class and

Abstract classes and pure virtual function

In the multi-state, the realization of virtual functions is usually the parent class is meaningless, the main contents are calling overridden subclass

Thus virtual function can be changed to a pure virtual function

Pure virtual function syntax:virtual 返回值类型 函数名 (参数列表)= 0 ;

When the class with a pure virtual function, also called the classAbstract class

Abstract class features :

  • Unable to instantiate an object
  • Subclasses must override the abstract class pure virtual function, otherwise it belongs to the abstract class

Example:

class Base
{
public:
	//纯虚函数
	//类中只要有一个纯虚函数就称为抽象类
	//抽象类无法实例化对象
	//子类必须重写父类中的纯虚函数,否则也属于抽象类
	virtual void func() = 0;
};

class Son :public Base
{
public:
	virtual void func() 
	{
		cout << "func调用" << endl;
	};
};

void test01()
{
	Base * base = NULL;
	//base = new Base; // 错误,抽象类无法实例化对象
	base = new Son;
	base->func();
	delete base;//记得销毁
}

int main() {

	test01();

	system("pause");

	return 0;
}
Published 47 original articles · won praise 3 · Views 1429

Guess you like

Origin blog.csdn.net/weixin_42076938/article/details/104751097