声明一个基类BassClass,有整型成员变量Number,构造其派生类DerivedClass,观察构造函数和析构函数的执行情况
时间: 2024-05-10 17:17:23 浏览: 137
以下是一个可能的实现方式:
```c++
#include <iostream>
class BassClass {
public:
int Number;
BassClass(int number) : Number(number) {
std::cout << "BassClass constructor called" << std::endl;
}
~BassClass() {
std::cout << "BassClass destructor called" << std::endl;
}
};
class DerivedClass : public BassClass {
public:
DerivedClass(int number) : BassClass(number) {
std::cout << "DerivedClass constructor called" << std::endl;
}
~DerivedClass() {
std::cout << "DerivedClass destructor called" << std::endl;
}
};
int main() {
DerivedClass dc(42);
return 0;
}
```
在执行程序时,可以看到以下输出:
```
BassClass constructor called
DerivedClass constructor called
DerivedClass destructor called
BassClass destructor called
```
这表明首先调用了基类的构造函数,然后调用了派生类的构造函数。当程序执行结束时,析构函数的调用顺序正好相反,先调用派生类的析构函数,再调用基类的析构函数。
阅读全文