写一个c++析构函数含有多重继承与派生
时间: 2023-12-06 12:44:14 浏览: 78
下面是一个含有多重继承与派生的C++程序,其中包含了多个类,每个类都有自己的析构函数实现。
```cpp
#include<iostream>
using namespace std;
class Base1 {
public:
Base1() { cout << "Base1 Constructor" << endl; }
virtual ~Base1() { cout << "Base1 Destructor" << endl; }
};
class Base2 {
public:
Base2() { cout << "Base2 Constructor" << endl; }
virtual ~Base2() { cout << "Base2 Destructor" << endl; }
};
class Derived1 : public Base1 {
public:
Derived1() { cout << "Derived1 Constructor" << endl; }
virtual ~Derived1() { cout << "Derived1 Destructor" << endl; }
};
class Derived2 : public Base2 {
public:
Derived2() { cout << "Derived2 Constructor" << endl; }
virtual ~Derived2() { cout << "Derived2 Destructor" << endl; }
};
class Derived3 : public Derived1, public Derived2 {
public:
Derived3() { cout << "Derived3 Constructor" << endl; }
virtual ~Derived3() { cout << "Derived3 Destructor" << endl; }
};
int main() {
Derived3 d;
return 0;
}
```
上述程序中,我们定义了四个类:`Base1`、`Base2`、`Derived1`和`Derived2`,其中`Derived1`继承自`Base1`,`Derived2`继承自`Base2`。然后我们定义了一个类`Derived3`,它同时从`Derived1`和`Derived2`中派生出来,即实现了多重继承。在`main()`函数中,我们创建了一个`Derived3`的对象`d`,然后程序运行结束时,会自动调用各个类的析构函数进行内存清理。
输出结果如下:
```
Base1 Constructor
Derived1 Constructor
Base2 Constructor
Derived2 Constructor
Derived3 Constructor
Derived3 Destructor
Derived2 Destructor
Base2 Destructor
Derived1 Destructor
Base1 Destructor
```
可以看到,程序运行结束后,各个类的析构函数按照派生关系的顺序依次被调用,完成了内存的清理工作。
阅读全文