代码正在打印所有构造函数。我读到当我们从另一个类派生一个类时,构造函数不会被继承。那么为什么 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;
}
最佳答案
当您阅读的文档说构造函数“不被继承”时,这意味着如果类 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; }
};
关于c++ - 如果构造函数不是继承的,为什么要调用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41383722/