定义object类,有weight属性及相应的操作函数,由此派生出box类,增加Height和width属性及相应的操作函数,声明一个box对象,观察构造函数与析构函数的调用顺序。
时间: 2023-05-20 07:06:14 浏览: 109
好的,这是一个关于面向对象编程的问题。下面是一个示例代码,定义了一个object类和一个box类,以及一个box对象,并观察了构造函数和析构函数的调用顺序。
```cpp
#include <iostream>
using namespace std;
class object {
public:
object(double w = 0) : weight(w) {
cout << "object constructor called" << endl;
}
virtual ~object() {
cout << "object destructor called" << endl;
}
double getWeight() const {
return weight;
}
void setWeight(double w) {
weight = w;
}
private:
double weight;
};
class box : public object {
public:
box(double w = 0, double h = 0, double wd = 0) : object(w), height(h), width(wd) {
cout << "box constructor called" << endl;
}
~box() {
cout << "box destructor called" << endl;
}
double getHeight() const {
return height;
}
void setHeight(double h) {
height = h;
}
double getWidth() const {
return width;
}
void setWidth(double wd) {
width = wd;
}
private:
double height;
double width;
};
int main() {
box b(10, 20, 30);
cout << "weight: " << b.getWeight() << endl;
cout << "height: " << b.getHeight() << endl;
cout << "width: " << b.getWidth() << endl;
return 0;
}
```
输出结果如下:
```
object constructor called
box constructor called
weight: 10
height: 20
width: 30
box destructor called
object destructor called
```
可以看到,构造函数的调用顺序是先调用基类的构造函数,再调用派生类的构造函数;析构函数的调用顺序是先调用派生类的析构函数,再调用基类的析构函数。
阅读全文