C++程序设计:分别创建B,C,D三个类,D从B类派生,并具有C类对象c1和c2对象成员。验证在创建D类对象时各类的构造函数和析构函数的条用次序。实现代码并写出运行结果。
时间: 2024-03-25 22:39:48 浏览: 63
以下是实现代码:
```cpp
#include <iostream>
using namespace std;
class B {
public:
B() { cout << "B constructor called" << endl; }
~B() { cout << "B destructor called" << endl; }
};
class C {
public:
C() { cout << "C constructor called" << endl; }
~C() { cout << "C destructor called" << endl; }
};
class D : public B {
public:
D() {
cout << "D constructor called" << endl;
c1 = new C();
c2 = new C();
}
~D() {
delete c1;
delete c2;
cout << "D destructor called" << endl;
}
private:
C* c1;
C* c2;
};
int main() {
D d;
return 0;
}
```
运行结果:
```
B constructor called
C constructor called
C constructor called
D constructor called
D destructor called
C destructor called
C destructor called
B destructor called
```
解释:
1. 创建D类对象时,首先会调用B类的构造函数,输出"B constructor called"。
2. 接着调用D类的构造函数,输出"D constructor called"。
3. 在D类的构造函数中,创建了两个C类对象并分别赋值给c1和c2指针。
4. D类对象的析构函数被调用时,先释放c1和c2指向的内存,输出"C destructor called"。
5. 然后调用B类的析构函数,输出"B destructor called"。
6. 最后调用D类的析构函数,输出"D destructor called"。
阅读全文