#include <iostream> using namespace std; class Base1 { public: Base1(int m_a):m_A(m_a){ cout<<"base1 构造"<<endl; } ~Base1(){ cout<<"base1 析构"<<endl; } int m_A; }; class Base2 { public: Base2(int m_a):m_A(m_a){ cout<<"base2 构造"<<endl; } ~Base2(){ cout<<"base2 析构"<<endl; } int m_A; }; class temp{ public: temp(int a_):a(a_){ cout<<"temp 构造"<<endl; } ~temp(){ cout<<"temp 析构"<<endl; } int a; }; class Son : public Base2, public Base1 //构造/析构函数的顺序只受继承顺序的影响 { public: Son(int a1, int a2, int a3):Base1(a1),Base2(a2), //构造/析构函数的顺序不受构造函数写法先后的影响 { m_C = 300; } public: int m_C; temp t; }; int main() { Son s(2,3,5); return 0; }//先执行 类构造函数,再执行 类构造函数,最后执行 类构造函数,析构函数相反
时间: 2024-01-12 10:03:16 浏览: 70
代码中的注释有点问题,应该是:先执行基类构造函数,再执行成员变量构造函数,最后执行派生类构造函数;析构函数的执行顺序与构造函数相反。
补充完整的代码如下:
```
#include <iostream>
using namespace std;
class Base1 {
public:
Base1(int m_a):m_A(m_a){
cout<<"base1 构造"<<endl;
}
~Base1(){
cout<<"base1 析构"<<endl;
}
int m_A;
};
class Base2 {
public:
Base2(int m_a):m_A(m_a){
cout<<"base2 构造"<<endl;
}
~Base2(){
cout<<"base2 析构"<<endl;
}
int m_A;
};
class temp{
public:
temp(int a_):a(a_){
cout<<"temp 构造"<<endl;
}
~temp(){
cout<<"temp 析构"<<endl;
}
int a;
};
class Son : public Base2, public Base1 {
public:
Son(int a1, int a2, int a3):Base1(a1),Base2(a2),t(a3),m_C(300){
cout<<"Son 构造"<<endl;
}
public:
int m_C;
temp t;
};
int main() {
Son s(2,3,5);
return 0;
}
```
输出结果为:
```
base1 构造
base2 构造
temp 构造
Son 构造
temp 析构
base2 析构
base1 析构
```
阅读全文