![](/img/trans.png)
[英]Subclass from a Superclass with no default constructor, without calling any other constructors
[英]Calling the superclass' constuctor twice in the subclass' constructor
我有一个用户定义的类,例如A。我有另一个用户定义的类B,它公开地扩展了A。
定义B的构造函数时,必须在B的构造函数的成员初始化器列表中调用A的构造函数,否则编译器将调用默认的构造函数。
class A {
int a;
public:
A(int x = 0) {
a = x;
}
};
class B : public A {
int b;
public:
B(int x = 0) : A(2*x) {
b = x;
}
};
现在,我了解了所有这些背后的逻辑。 但是,我想知道的是,当我这样做时会发生什么:
class A {
int a;
public:
A(int x = 0) {
a = x;
}
};
class B : public A {
int b;
public:
B(int x = 0) {
A(2*x);
b = x;
}
};
我的意思是,我们都知道编译器将在进入B的构造函数主体之前调用A的默认构造函数。 现在,B的构造函数主体的第一行是调用A的另一个构造函数(带有参数)。 那么,这会导致什么呢? 每当创建子类的对象时,都将调用超类的两个不同的构造函数。 请说明会发生什么...将创建两个对象还是什么。
这不会调用正在初始化的B
的A
子对象的构造函数。 而是创建并销毁类型为A
的临时对象。 调用基础子对象的构造函数的唯一方法是通过初始化程序列表,如第一个示例所示。
现在,B的构造函数主体的第一行是调用A的另一个构造函数(带有参数)。 那么,这会导致什么呢?
它构造一个临时A
并且立即丢弃该临时对象。 该调用与初始化B
的A
部分无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.