C++中的虚函数
虚函数是在基类中声明并由派生类重新定义(重写)的成员函数。当您使用指针或对基类的引用来引用派生类对象时,可以为该对象调用一个虚函数并执行该派生类的函数版本。
C++中的纯虚函数
C++中的纯虚函数(或抽象函数)是一个虚函数,我们没有实现,只声明它。通过在声明中分配0来声明纯虚函数。
虚函数与纯虚函数之间的相似性
- 这些是运行时多态性的概念。
- 原型,即两个功能的声明在整个程序中保持相同。
- 这些函数不能是全局或静态的。
C++中虚函数和纯虚函数之间的区别
Virtual function | Pure virtual function |
---|---|
A virtual function is a member function of base class which can be redefined by derived class. | A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract. |
Classes having virtual functions are not abstract. | Base class containing pure virtual function becomes abstract. |
Syntax:
|
Syntax:
|
Definition is given in base class. | No definition is given in base class. |
Base class having virtual function can be instantiated i.e. its object can be made. | Base class having pure virtual function becomes abstract i.e. it cannot be instantiated. |
If derived class do not redefine virtual function of base class, then it does not affect compilation. | If derived class do not redefine virtual function of base class, then no compilation error but derived class also becomes abstract just like the base class. |
All derived class may or may not redefine virtual function of base class. | All derived class must redefine pure virtual function of base class otherwise derived class also becomes abstract just like base class. |
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。