用简单的cpp编写创建Base类Base拥有一个私有的数据成员x显示写出Base的构造和析构并通过构造函数初始化私有成员x。Derived类公有继承Base类Derived拥有一个私有成员y显示写出Derived的构造和析构这个程序如何运行的呢
这个程序并没有提供具体的运行方式,需要根据具体情况进行调用和运行。以下是简单的代码实现:
#include <iostream>
class Base {
private:
int x;
public:
Base(int _x) : x(_x) {
std::cout << "Base constructor called" << std::endl;
}
~Base() {
std::cout << "Base destructor called" << std::endl;
}
};
class Derived : public Base {
private:
int y;
public:
Derived(int _x, int _y) : Base(_x), y(_y) {
std::cout << "Derived constructor called" << std::endl;
}
~Derived() {
std::cout << "Derived destructor called" << std::endl;
}
};
int main() {
Derived d(1, 2);
return 0;
}
运行结果为:
Base constructor called
Derived constructor called
Derived destructor called
Base destructor called
``
原文地址: https://www.cveoy.top/t/topic/ci9e 著作权归作者所有。请勿转载和采集!