虚函数背后的秘密

#include <iostream>
using namespace std;

class Base
{
public:
 virtual void fun()
 {
  cout << "Base::fun" << endl;
 }
 void show()
 {
  fun();
 }
};

class Drive: public Base
{
public:
 virtual void fun()
 {
  cout << "Drive::fun" << endl;
 }
};

int main()
{
 Drive d;
 d.show();
 d.fun();
 return 0;
}

Drive::fun
Drive::fun

这个程序清楚地示范了基类的函数是如何调用派生类的虚函数的。这一技术被用于不同的框架中,例如MFC和设计模式(比如Template Design Pattern)。现在你可以修改一下这个程序来看看它的行为,我将要在基类的构造函数中调用虚函数,而不是普通的成员函数。

#include <iostream>
using namespace std;

class Base
{
public:
 Base()
 {
  fun();
 }
 virtual void fun()
 {
  cout << "Base::fun" << endl;
 }
};

class Drive: public Base
{
public:
 virtual void fun()
 {
  cout << "Drive::fun" << endl;
 }
};

int main()
{
 Drive d;
 d.fun();
 return 0;
}

Base::fun
Drive::fun
这个程序表明,我们不能在基类的构造函数中调用派生类的虚函数。


 

原文地址:https://www.cnblogs.com/byfei/p/3112232.html