首页 > 试题广场 >

定义一个矩形类,有长、宽两个属性,有成员函数计算矩形的面积

[问答题]

定义一个矩形类,有长、宽两个属性,有成员函数计算矩形的面积

推荐

解:

#include <iostream.h>
class Rectangle
{
public:
Rectangle(float len, float width)
{
Length = len;
Width = width;
}
~Rectangle(){};
float GetArea() { return Length * Width; }
float GetLength() { return Length; }
float GetWidth() { return Width; }
private:
float Length;
float Width;
};
void main()
{
float length, width;
cout << "请输入矩形的长度:";
cin >> length;
cout << "请输入矩形的宽度:";
cin >> width;
Rectangle r(length, width);
cout << "长为" << length << "宽为" << width << "的矩形的面积为:"
<< r.GetArea () << endl;
}

程序运行输出:

请输入矩形的长度:5

请输入矩形的宽度:4

长为 5 宽为 4 的矩形的面积为:20



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