编写程序声明一个基类BaseClass,构造其派生类DerivedClass,在构造函数和析构函数中用cout输出提示信息,观察构造函数和析构函数的执行情况
时间: 2024-02-12 20:07:08 浏览: 150
以下是示例代码:
```c++
#include <iostream>
using namespace std;
class BaseClass {
public:
BaseClass() {
cout << "BaseClass constructor called." << endl;
}
virtual ~BaseClass() {
cout << "BaseClass destructor called." << endl;
}
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {
cout << "DerivedClass constructor called." << endl;
}
~DerivedClass() {
cout << "DerivedClass destructor called." << endl;
}
};
int main() {
DerivedClass obj;
return 0;
}
```
运行结果为:
```
BaseClass constructor called.
DerivedClass constructor called.
DerivedClass destructor called.
BaseClass destructor called.
```
从结果可以看出,当创建DerivedClass对象时,首先会调用BaseClass的构造函数,然后调用DerivedClass的构造函数;当对象被销毁时,先调用DerivedClass的析构函数,再调用BaseClass的析构函数。这是因为在派生类的构造函数和析构函数中,会自动调用其基类的对应函数。
阅读全文