定义一个基类Object,有数据成员weight及相应的操作函数,由此派生出Box类,增加数据成员height和width及相应的操作函数,声明一个Box对象,观察构造函数与析构函数的调用顺序。

发布时间 2023-04-10 19:51:28作者: 笠大

定义一个基类Object,有数据成员weight及相应的操作函数,由此派生出Box类,增加数据成员height和width及相应的操作函数,声明一个Box对象,观察构造函数与析构函数的调用顺序。

#include<bits/stdc++.h>
using namespace std;
class Object {
protected:
	double weight;
public:
	Object(double a) {
		weight = a;
		cout << "constructed O" << endl;
	}
	double func1();
	~Object() {
		cout << "destroyed O" << endl;
	}
};
class Box :public Object {
private:
	double height,width;
public:
	Box(double c,double a,double b):Object(c),height(a),width(b){
		cout << "constructed B" << endl;
	}
	~Box() {
		cout << "destroyed B" << endl;
	}
	void dis() {
		cout << "weight= " << weight << " height= " << height << " width= " << width << endl;
	}
};
int main()
{
	Box b1(2,3.4,6.4);
	b1.dis();

}


结果为:

constructed O
constructed B
weight= 2 height= 3.4 width= 6.4
destroyed B
destroyed O