sam*_*her 4 c++ oop inheritance multiple-inheritance
代码正在打印所有构造函数.我读到当我们从另一个类派生一个类时,构造函数不会被继承.那么为什么创建c是从b和调用构造函数a
class A
{
public:
A() { cout << "A's constructor called" << endl; }
};
class B
{
public:
B() { cout << "B's constructor called" << endl; }
};
class C: public B, public A // Note the order
{
public:
C() { cout << "C's constructor called" << endl; }
};
int main()
{
C c;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当您阅读的文档表示构造函数是"未继承"时,它意味着如果类A定义了构造函数A::A(int x),那么子类B将不会自动拥有一个构造函数int.
但是,仍然需要初始化父类的值; 否则,父对象可能处于无效状态.构造函数用于初始化类,因此必须从子构造函数的初始化列表中调用其中一个父类的构造函数.如果父类具有默认构造函数,则默认情况下会调用该构造函数.这就是你在你的例子中看到的.如果父级未提供默认构造函数,则必须指定要调用的构造函数:
class A
{
public:
A(int x) { cout << "A's constructor called" << endl; }
};
class C: public A
{
public:
C()
: A(7) /* compilation will fail without this line */
{ cout << "C's constructor called" << endl; }
};
Run Code Online (Sandbox Code Playgroud)