📜  C++中虚函数和纯虚函数的区别

📅  最后修改于: 2021-09-13 02:13:25             🧑  作者: Mango

C++中的虚函数
虚函数是在基类中声明并由派生类重新定义(覆盖)的成员函数。当您使用指针或对基类的引用来引用派生类对象时,您可以为该对象调用虚拟函数并执行派生类版本的函数。

C++ 中的纯虚函数
C++ 中的纯虚函数(或抽象函数)是我们没有实现的虚函数,我们只声明它。纯虚函数通过在声明中赋值 0 来声明。

虚函数和纯虚函数的相似之处

  1. 这些是运行时多态的概念。
  2. 原型即两个函数的声明在整个程序中保持不变。
  3. 这些函数不能是全局的或静态的。

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:
virtual()
{
    // code
}
Syntax:
virtual()
    = 0;
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 等的准备工作,请参阅完整的面试准备课程