【C++作业】求高手帮忙解答一下,明天要用! 第二题

来源:百度知道 编辑:UC知道 时间:2024/06/19 01:35:19
定义一个矩形类Rectangle,矩形的左上角(Left,Top)与右下角坐标(Right,Bottom)定义为保护数据成员。用公有成员函数Diagonal()计算出矩形对角线的长度,公有成员函数Show()显示矩形左上角与右下角坐标及对角线长度。在主函数中用new运算符动态建立矩形对象r1,初值为(10,10,20,20)。然后调用Show()显示矩形左上角与右下角坐标及对角线长度。最后用delete运算符回收为矩形动态分配的存储空间。

#include <conio.h>
#include <iostream>
#include <math.h>

using namespace std;

class Rectangle
{
public:
Rectangle( int l, int t, int r, int b )
{
left = l, top = t, right = r, bottom = b;
}
float Diagonal()
{
return sqrt( (right-left)*(right-left) + (bottom-top)*(bottom-top) );
}

void Show()
{
cout<<left<<", "<<top<<", "<<right<<", "<<bottom<<endl;
cout<<Diagonal()<<endl;
}

protected:
int left, top, right, bottom;
};

void main()
{
Rectangle *r1;

r1 = new Rectangle( 10, 10, 20, 20 );
r1->Show();

delete r1;
}