C++练习
1.设计一个矩形类,矩形类的数据成员包括:矩形的左上角的坐标和右下角坐标, 数据类型根据需要自行设定;矩形类的函数成员包括:计算矩形周长与面积、构造函数等,其他成员函数可自行添加和完善。编写测试代码,创建一个矩形对象,然后测试该矩形对象的各个成员函数。
#include <iostream>
#include <stdlib.h>
using namespace std;
class Point
{
int x, y;
public:
Point(int a, int b);
int GetX() {return x;}
int GetY() {return y;}
};
Point::Point(int a, int b)
{
x = a;
y = b;
}
class Shape
{
Point rp, lp;
public:
Shape(int rx, int ry, int lx, int ly) :rp(rx, ry), lp(lx, ly) {}
int GetArea(); //求面积。
int GetPerimeter(); //求周长
};
int Shape::GetArea()
{
int s;
s = (rp.GetX() - lp.GetX())*(lp.GetY() - rp.GetY());
return s;
}
int Shape::GetPerimeter()
{
int c;
c = (rp.GetX() - lp.GetX()) * 2 + (lp.GetY() - rp.GetY()) * 2;
return c;
}
int main()
{
int rx, ry, lx, ly;
cout << "请输入右下角x坐标:";
cin >> rx;
cout << "请输入右下角y坐标:";
cin >> ry;
cout << "请输入左下角x坐标:";
cin >> lx;
cout << "请输入左下角y坐标:";
cin >> ly;
Shape test(rx, ry, lx, ly);
cout << "矩形的面积为:"<<test.GetArea()<<endl;
cout << "矩形的周长为:" << test.GetPerimeter() << endl;
system("PAUSE");
}