创建Base类,Base拥有一个私有的数据成员x,显示写出Base的构造和析构,并通过构造函数初始化私有成员x,具有print函数输出数据成员。 Derived类公有继承Base类,Derived拥有一个私有成员y,显示写出Derived的构造和析构。 具有print函数输出数据成员。 最后通过主函数实现。
时间: 2024-03-25 08:39:25 浏览: 13
好的,以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Base {
private:
int x;
public:
Base(int _x) : x(_x) {
cout << "Base构造函数被调用" << endl;
}
~Base() {
cout << "Base析构函数被调用" << endl;
}
void print() {
cout << "Base类的x值为:" << x << endl;
}
};
class Derived : public Base {
private:
int y;
public:
Derived(int _x, int _y) : Base(_x), y(_y) {
cout << "Derived构造函数被调用" << endl;
}
~Derived() {
cout << "Derived析构函数被调用" << endl;
}
void print() {
Base::print();
cout << "Derived类的y值为:" << y << endl;
}
};
int main() {
Derived d(10, 20);
d.print();
return 0;
}
```
解析:
- Base类有一个私有成员变量x,构造函数初始化x,析构函数用于资源的释放;
- Derived类公有继承Base类,有一个私有成员变量y,构造函数调用Base类的构造函数并初始化y,析构函数用于资源的释放;
- Base类的print函数输出x的值,Derived类的print函数先调用Base类的print函数再输出y的值;
- 在主函数中创建Derived类的对象并调用print函数输出x和y的值。