源程序:
//1.設計一個點類 Point,再設計一個矩形類,矩形類使用 Point 類的兩個坐標點作為矩形的對
//角頂點。並可以輸出 4 個坐標值和面積。使用測試程序驗證程序。
#include <iostream>
using namespace std;
class Point //點類
{
private:
int x, y;//私有成員變量,坐標
public :
Point()//無參數的構造方法,對 xy 初始化
{
x = 0;
y = 0;
}
Point(int a, int b)//又參數的構造方法,對 xy 賦值
{
x = a;
y = b;
}
void setXY(int a, int b)//設置坐標的函數
{
x = a;
y = b;
}
int getX()//得到 x 的方法
{
return x;
}
int getY()//得到有的函數
{
return y;
}
};
class Rectangle //矩形類
{
private:
Point point1, point2, point3, point4;//私有成員變量,4 個點的對象
public :
Rectangle();//類 Point 的無參構造函數已經對每個對象做初始化啦,這里不用對每個點多初始化了
Rectangle(Point one, Point two)//用點對象做初始化的,構造函數,1 和 4 為對角頂點
{
point1 = one;
point4 = two;
init();
}
Rectangle(int x1, int y1, int x2, int y2)//用兩對坐標做初始化,構造函數,1 和 4為對角頂點
{
point1.setXY(x1, y1);
point4.setXY(x2, y2);
init();
}
void init()//給另外兩個點做初始化的函數
{
point2.setXY(point4.getX(), point1.getY() );
point3.setXY(point1.getX(), point4.getY() );
}
void printPoint()//打印四個點的函數
{
cout<<"A:("<< point1.getX() <<","<< point1.getY() <<")"<< endl;
cout<<"B:("<< point2.getX() <<","<< point2.getY() <<")"<< endl;
cout<<"C:("<< point3.getX() <<","<< point3.getY() <<")"<< endl;
cout<<"D:("<< point4.getX() <<","<< point4.getY() <<")"<< endl;
}
int getArea()//計算面積的函數
{
int height, width, area;
height = point1.getY() - point3.getY();
width = point1.getX() - point2.getX();
area = height * width;
if(area > 0)
return area;
else
return -area;
}
};
void main()
{
Point p1(-15, 56), p2(89, -10);//定義兩個點
Rectangle r1(p1, p2);//用兩個點做參數,聲明一個矩形對象 r1
Rectangle r2(1, 5, 5, 1);//用兩隊左邊,聲明一個矩形對象 r2
cout<<"矩形 r1 的 4 個定點坐標:"<< endl;
r1.printPoint();
cout<<"矩形 r1 的面積:"<< r1.getArea() << endl;
cout<<"\n 矩形 r2 的 4 個定點坐標:"<< endl;
r2.printPoint();
cout<<"矩形 r2 的面積:"<< r2.getArea() << endl;
}
運行結果: