原文地址:https://blog.csdn.net/gao1440156051/article/details/45670715
父类使用虚函数是为了让子类重写,那子类重写的时候也需要带virtual关键字吗?比如:
class Base{
virtual bool init();
};
class Derived{
virtual bool init(); //这里的vitual是必须的吗?好像不用也能编译通过呃…..
};
c++规定,当一个成员函数被声明为虚函数后,其派生类中的同名函数都自动成为虚函数。因此,在子类从新声明该虚函数时,可以加,也可以不加,但习惯上每一层声明函数时都加virtual,使程序更加清晰。
#include <iostream> #include <unordered_map> using namespace std; class BaseClass { public: virtual void SayHello() { cout << "BaseClass" << endl; } }; class SonClass : public BaseClass { public: void SayHello() { cout << "SonClass" << endl; } }; class GrandSonClass : public SonClass { public: void SayHello() { cout << "GrandSonClass" << endl; } }; int main() { BaseClass* ptr = new GrandSonClass(); ptr->SayHello(); //输出: GrandSonClass (子类没用virtual, 孙子类依然有virtual效果) system("pause"); return 0; }
标签:函数,子类,C++,关键字,init,virtual,class From: https://www.cnblogs.com/barrysgy/p/17658835.html