对上题的程序进行修改,在main中用new的方式创建一个Rect对象,调用相关方法,最后用delete删除对象。观察分析程序的运行结果。

运用面向对象程序设计方法实现一个长方形类Rect,要求能设定长方形的长和宽,能计算长方形的面积和周长,在main中创建一个长方形。
#include"iostream"
using namespace std;

class Rect
{
private:
double length;
double width;
public:
void side(double l,double w);
void Area();
void Peri();
};
void Rect::side(double l,double w)
{
length=l;
width=w;
}
void Rect::Area()
{
cout<<"Area="<<length*width<<endl;
}
void Rect::Peri()
{
cout<<"Peri="<< 2*(length+width)<<endl;
}
int main()
{
Rect r;
r.side(4,7);
r.Area();
r.Peri();
return 0;
}

程序基本上没有什么问题,但是可以改进下,比如计算面积、周长的代码,不要输出,而是返回计算结果:
int Rect::Area() { return length*width; }
让主程序去输出
cout<<"Area="<<r.Area() << endl;