zoukankan      html  css  js  c++  java
  • 虚函数背后的秘密

    #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
    这个程序表明,我们不能在基类的构造函数中调用派生类的虚函数。


     

  • 相关阅读:
    【模板】并查集
    P1063能量项链
    多维动归第一题
    7.14测试
    7.12测试
    7.10测试
    几种display:table-cell的应用
    instanceof和typeof的区别
    右侧悬浮广告
    JavaScript判断浏览器类型及版本
  • 原文地址:https://www.cnblogs.com/byfei/p/3112232.html
Copyright © 2011-2022 走看看