首页 > 试题广场 >

定义 object 类,有 weight 属性及相应的操作函

[问答题]

定义 object 类,有 weight 属性及相应的操作函数,由此派生出 box 类,增加 Height和 width 属性及相应的操作函数,声明一个box对象,观察构造函数与析构函数的调用顺序。

推荐

解:

#include <iostream.h>
class object
{
private:
int Weight;
public:
object()
{
cout << "构造 object 对象" << endl;
Weight = 0;
}
int GetWeight(){ return Weight;}
void SetWeight(int n){ Weight = n;}
~object() { cout << "析构 object 对象" << endl;}
};
class box : public object
{
private:
int Height,Width;
public:
box()
{
cout << "构造 box 对象" << endl;
Height = Width = 0;
}
int GetHeight(){ return Height;}
void SetHeight(int n){ Height = n;}
int GetWidth(){ return Width;}
void SetWidth(int n){ Width = n;}
~box() { cout << "析构 box 对象" << endl;}
};
void main()
{
box a;
}

程序运行输出:

构造 object 对象

构造 box 对象

析构 box 对象

析构 object 对象



发表于 2018-04-18 20:47:47 回复(0)