c++声明一个基类BaseClass,有整型成员变量Number,构造其派生类DerivedClass,观察构造函数和析构函数的执行情况。
时间: 2023-12-14 17:38:57 浏览: 106
C++中构造函数和析构函数
可以按照如下代码实现:
```c++
#include <iostream>
using namespace std;
class BaseClass {
public:
int Number;
BaseClass() {
cout << "BaseClass default constructor called." << endl;
Number = 0;
}
BaseClass(int num) {
cout << "BaseClass constructor with parameter called." << endl;
Number = num;
}
~BaseClass() {
cout << "BaseClass destructor called." << endl;
}
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {
cout << "DerivedClass default constructor called." << endl;
}
DerivedClass(int num) : BaseClass(num) {
cout << "DerivedClass constructor with parameter called." << endl;
}
~DerivedClass() {
cout << "DerivedClass destructor called." << endl;
}
};
int main() {
cout << "Create a BaseClass object." << endl;
BaseClass baseObj(10);
cout << "Number in BaseClass: " << baseObj.Number << endl;
cout << endl << "Create a DerivedClass object." << endl;
DerivedClass derivedObj(20);
cout << "Number in BaseClass: " << derivedObj.Number << endl;
return 0;
}
```
运行结果如下:
```
Create a BaseClass object.
BaseClass constructor with parameter called.
Number in BaseClass: 10
BaseClass destructor called.
Create a DerivedClass object.
BaseClass constructor with parameter called.
DerivedClass constructor with parameter called.
Number in BaseClass: 20
DerivedClass destructor called.
BaseClass destructor called.
```
从输出结果可以看出,当创建 BaseClass 对象时,BaseClass 的构造函数会被调用,当对象被销毁时,BaseClass 的析构函数会被调用。当创建 DerivedClass 对象时,先调用 BaseClass 的构造函数,再调用 DerivedClass 的构造函数;当对象被销毁时,先调用 DerivedClass 的析构函数,再调用 BaseClass 的析构函数。
阅读全文