以下面的例子举例:
#include<iostream>
using namespace std;
class B {
public:
B() { cout << "B0::B()" << endl; }
B(int a) { cout << "B1::B()" <<" "<< "a=" << a << endl; }
~B() { cout << "~B()" << endl; }
};
class D :public B {
public:
D() { cout << "D0::D()" << endl; }
D(int a) { cout << "D1::D()" <<" "<< "a=" << a << endl; }
~D() { cout << "~D()" << endl; }
};
下面是各种main()函数的情况
1.
int main() {
B b;
return 0;
}
int main() {
D d;
return 0;
}
int main() {
B b = B(); // //只有一个B的对象,调用的是B()构造函数
B b1 = B(1); //只有一个B的对象,调用的是B(int a)构造函数
return 0;
}
int main() {
D d = D(); //只有一个D的对象,先调用B(),再调用D()
D d1 = D(1); //只有一个D的对象,先调用B(),再调用D(int a)
return 0;
}
int main() {
B b = D(); //先调用B(),再调用D(),但是D()不会再调用基类构造
return 0;
}
注意对比:改为
int main() {
B b;
D();
return 0;
}
int main() {
B b = D(1); //先调用B(),再调用D(int a),但是D(int a)不会再调用基类构造
return 0;
}
int main() {
B* d = new B; //调用B()
/* B* d = new B(1); 调用B(int a) */
delete d; //有此行代码才会执行~B()
return 0;
}
int main() {
B* d = new D; //先调用B(),在调用D()
/* B* d = new D(1); 先调用B(),在调用D(int a) */
delete d; //注意:此行代码会调用~B(),但不会调用~D()
return 0;
}
另外,若有对象的复制操作,则只会调用拷贝构造函数,而不会调用其他的构造函数。