在C++中,类的继承构造顺序遵循以下规则:
以下是一个简单的例子,展示了类的继承构造顺序:
#include <iostream> class Base { public: Base() { std::cout << "Base constructor called" << std::endl; } }; class Derived : public Base { public: int x; Derived(int a) : x(a) { std::cout << "Derived constructor called" << std::endl; } }; int main() { Derived d(10); return 0; }
输出结果:
Base constructor called Derived constructor called
在这个例子中,首先调用基类Base
的构造函数,然后调用派生类Derived
的构造函数。在派生类构造函数中,使用成员初始化列表初始化成员变量x
。