定义一个基类Object类,有数据成员weight及相应的操作函数,由此派生出Box类,增加数据成员height和width及相应的操作函数,声明一个Box对象,观察构造函数与析构函数的调用顺序。
时间: 2024-05-12 13:20:41 浏览: 12
以下是Object类和Box类的定义:
```c++
class Object {
protected:
double weight;
public:
Object(double w = 0) : weight(w) { cout << "Object constructor called." << endl; }
virtual ~Object() { cout << "Object destructor called." << endl; }
void setWeight(double w) { weight = w; }
double getWeight() const { return weight; }
};
class Box : public Object {
private:
double height;
double width;
public:
Box(double h = 0, double w = 0, double weight = 0) : Object(weight), height(h), width(w) {
cout << "Box constructor called." << endl;
}
~Box() { cout << "Box destructor called." << endl; }
void setHeight(double h) { height = h; }
void setWidth(double w) { width = w; }
double getVolume() const { return height * width * getWeight(); }
};
```
以下是主函数中的代码:
```c++
int main() {
Box b(2, 3, 4);
cout << "Box weight: " << b.getWeight() << endl;
cout << "Box volume: " << b.getVolume() << endl;
return 0;
}
```
构造函数和析构函数的调用顺序如下:
```
Object constructor called.
Box constructor called.
Box weight: 4
Box volume: 24
Box destructor called.
Object destructor called.
```
可以看到,先调用Object类的构造函数,再调用Box类的构造函数,然后执行主函数中的代码,最后先调用Box类的析构函数,再调用Object类的析构函数。这与派生类继承基类的构造函数和析构函数的执行顺序相关。在创建派生类对象时,先调用基类的构造函数,再调用派生类的构造函数;在销毁派生类对象时,先调用派生类的析构函数,再调用基类的析构函数。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)