2.创建Base类,Base拥有一个私有的数据成员x,显示写出Base的构造和析构,并通过构造函数初始化私有成员x。 Derived类公有继承Base类,Derived拥有一个私有成员y,显示写出Derived的构造和析构。 最后通过主函数实现。(10分)
时间: 2024-03-24 09:41:10 浏览: 22
下面是代码实现:
```
#include <iostream>
using namespace std;
class Base{
private:
int x;
public:
Base(int X):x(X){ // 构造函数,初始化私有成员x
cout << "Base的构造函数被调用!" << endl;
}
~Base(){ // 析构函数
cout << "Base的析构函数被调用!" << endl;
}
};
class Derived : public Base{
private:
int y;
public:
Derived(int X, int Y):Base(X), y(Y){ // 构造函数,初始化私有成员y
cout << "Derived的构造函数被调用!" << endl;
}
~Derived(){ // 析构函数
cout << "Derived的析构函数被调用!" << endl;
}
};
int main(){
Derived d(1, 2); // 创建Derived类对象
return 0;
}
```
输出结果为:
```
Base的构造函数被调用!
Derived的构造函数被调用!
Derived的析构函数被调用!
Base的析构函数被调用!
```
可以看到,先调用了Base类的构造函数,再调用了Derived类的构造函数;最后先调用Derived类的析构函数,再调用Base类的析构函数。这是因为在创建Derived类对象时,先要创建它的基类对象,而在销毁Derived类对象时,先销毁它的派生类成员,再销毁基类对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)