设计一个Rectangle类。要求:
//(1)包含两个成员变量m_length和m_width,其默认值为1。
//(2)包含成员函数Perimeter()计算长方形的周长,Area()计算长方形面积。
//(3)包含成员函数SetWidth()和GetWidth()用来设置和得到m_width的值,SetLength()和GetLength()用来设置和得到m_length的值。Set…()函数应验证m_length和m_width均为0.0到20.0之间的浮点数。
//(4)编写主函数,测试Rectangle类。
#include<iostream>
using namespace std;
class Rectangle {
public:
//Perimeter()计算长方形的周长
double Perimeter() { return 2 * (m_length + m_width); }
//Area()计算长方形面积
double Area() { return m_length * m_width; }
//SetWidth()和GetWidth()用来设置和得到m_width的值
void SetWidth(double w) { m_width = w; }
double GetWidth() { return m_width; }
//SetLength()和GetLength()用来设置和得到m_length的值
void SetLength(double l) { m_length = l; }
double GetLength() { return m_length; }
//Set_()函数应验证m_length和m_width均为0.0到20.0之间的浮点数。
bool Set_() {
bool n = 1;
if (0 > m_length || 20 < m_length) {
cout << "length is not in 0.0 - 20.0" << endl;
n = 0;
}
if (0 > m_width || 20 < m_width) {
cout << "width is not in 0.0 - 20.0" << endl;
n = 0;
}
if (n)
cout << "length and width are both in 0.0 - 20.0" << endl;
return n;
}
private:
//两个成员变量m_length和m_width,其默认值为1
double m_length = 1;
double m_width = 1;
};
int main() {
Rectangle rec;
cout << "Length : " << rec.GetLength() << " " << "Width : " << rec.GetWidth() << endl;
rec.Set_();
cout << endl << endl;
rec.SetLength(5.2);
rec.SetWidth(4);
cout << "Length : " << rec.GetLength() << " " << "Width : " << rec.GetWidth() << endl;
rec.Set_();
cout << endl << endl;
rec.SetWidth(25);
cout << "Length : " << rec.GetLength() << " " << "Width : " << rec.GetWidth() << endl;
rec.Set_();
cout << endl << endl;
return 1;
}