设计一个长方体类,其长、宽和高属性默认为1,其成员函数计算长方体的体积。为该类的长、宽和高设置set和get函数。Set函数应验证长、宽和高均为8-50之间的浮点数。 要求包括:(1)定义无参的构造函数、析构函数、(2)在主函数中输入长方体长、宽、高(实参值),定义长方体类的对象,调用计算长方体类的体积的函数。
时间: 2023-02-05 18:50:35 浏览: 356
以下是用 C++ 语言描述的长方体类:
```
class Rectangle
{
private:
float length;
float width;
float height;
public:
// 构造函数,初始化长方体的长、宽、高
Rectangle(float l=1, float w=1, float h=1)
{
setLength(l);
setWidth(w);
setHeight(h);
}
// 析构函数
~Rectangle() {}
// set 函数,用于设置长、宽、高的值
void setLength(float l)
{
if (l > 8 && l < 50)
length = l;
else
length = 1;
}
void setWidth(float w)
{
if (w > 8 && w < 50)
width = w;
else
width = 1;
}
void setHeight(float h)
{
if (h > 8 && h < 50)
height = h;
else
height = 1;
}
// get 函数,用于获取长、宽、高的值
float getLength() { return length; }
float getWidth() { return width; }
float getHeight() { return height; }
// 计算长方体的体积
float getVolume() { return length * width * height; }
};
```
在主函数中,你可以这样调用:
```
int main()
{
// 定义一个长方体类的对象,并初始化
Rectangle rect(10, 20, 30);
// 调用 getVolume 函数,计算长方体的体积
float volume = rect.getVolume();
cout << "长方体的体积:" << volume << endl;
return 0;
}
```
阅读全文
相关推荐
















