为什么基类的构造函数方法被调用两次?
问题描述:
任何人都可以告诉我为什么基类的构造方法被调用两次?为什么基类的构造函数方法被调用两次?
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "default constructor of base class" << endl;
}
};
class B:public A{
public:
B(){
A();
cout << "default constructor of derived class" << endl;
}
};
int main(int argc, char **argv){
B b;
return 0;
}
而且我得到这个意想不到的结果:
default constructor of base class
default constructor of base class
default constructor of derived class
答
一旦构建在main
的B
对象的基子对象:
B b;
一旦构建临时A
对象的B
构造:
A();
也许你的意思是初始化A
子对象;这样做,在初始化器列表,而不是在构造函数体:
B() : A() {
cout << "default constructor of derived class" << endl;
}
虽然,在这种情况下,会做同样的事情离开它完全。
答
这将涉及两个呼叫基地的构造。
1) In the derived initializer list.
2) Your explicit call.
即每个成员都在初始化程序列表中构建。如果您不提供任何特定的构造函数,则使用默认的构造函数。
答
基类构造函数被调用两次,因为您在派生类ctor中创建了一个基类的临时对象。
您可能想要阅读有关ctor-init-list的内容。
答
这是因为你直接在B中调用A()。但是,在继承中,当默认构造函数未被覆盖时,首先调用基类的构造函数。
所以,只需在B的构造函数中删除A(),因为类A是基类,它的构造函数将首先被调用。