#include <iostream>
using namespace std;

class AA {
public:
    AA() { cout << 'Constructor of AA is called.' << endl; }
    virtual void fn() { cout << 'AA function is called.' << endl; }
};

class BE : public AA {
public:
    BE() { cout << 'Constructor of BB is called.' << endl; }
    void fun() { cout << 'BB function is called.' << endl; }
};

int main() {
    BE b;
    b.fn();
    b.fun();
    return 0;
}

输出结果:

'Constructor of AA is called.' 'Constructor of BB is called.' 'AA function is called.' 'BB function is called.'

解释:

  1. 构造函数调用顺序: 由于 BE 类继承自 AA 类,因此在创建 BE 对象 b 时,首先会调用 AA 类的构造函数,然后调用 BE 类的构造函数。

  2. 虚函数动态绑定: 由于 fn() 函数在 AA 类中被声明为 virtual,因此 b.fn() 会根据对象的实际类型进行动态绑定。由于 bBE 类型的对象,所以最终调用的是 BE 类中 fn() 函数的实现,即输出 'AA function is called.'

  3. 普通函数调用: b.fun() 调用的是 BE 类中的 fun() 函数,因此输出 'BB function is called.'

总结: 该代码示例展示了 C++ 中多态性、虚函数、构造函数调用顺序等关键概念,帮助理解这些概念是如何协同工作的。


原文地址: https://www.cveoy.top/t/topic/j9Yo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录