用C++写一个基类,一个派生类,一个派生的派生,输出他们构造函数、析构函数执行的顺序
时间: 2023-05-31 15:03:16 浏览: 176
以下是用C++写的例子,因为C语言不支持类的概念:
```
#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << "Base Constructor" << endl;
}
virtual ~Base() {
cout << "Base Destructor" << endl;
}
};
class Derived : public Base {
public:
Derived() {
cout << "Derived Constructor" << endl;
}
~Derived() {
cout << "Derived Destructor" << endl;
}
};
class SubDerived : public Derived {
public:
SubDerived() {
cout << "SubDerived Constructor" << endl;
}
~SubDerived() {
cout << "SubDerived Destructor" << endl;
}
};
int main() {
SubDerived subDerived;
return 0;
}
```
输出结果为:
```
Base Constructor
Derived Constructor
SubDerived Constructor
SubDerived Destructor
Derived Destructor
Base Destructor
```
可以看到,构造函数的执行顺序是从基类到派生类,析构函数的执行顺序则相反,从派生类到基类。这是因为在创建对象时,先创建基类,再创建派生类,而在销毁对象时,则是先销毁派生类,再销毁基类。
阅读全文