題目
設計一個點類Point,再設計一個矩形類,矩形類使用Point類的兩個坐標點作為矩形的對角頂點。并可以輸出4個坐標值和面積。
分析
1.點類,自然維護的是一個點的坐標,
#include < iostream >
using namespace std;
class Point{//點類
private:
int x, y;//私有成員變量,坐標
public :
Point()//無參數的構造方法,對xy初始化
Point(int a, int b)
void setXY(int a, int b)
int getX()//得到x的方法
int getY()//得到有的函數
};
2.矩形類,有兩個點就能確定了
如果希望寫的完整,那么就要增加一個函數init(),維護另外兩個點,因為兩個對角的點坐標有一定的相關性。
class Rectangle //矩形類
{
private:
Point point1, point2;
public :
Rectangle();//類Point的無參構造函數已經對每個對象做初始化啦,這里不用對每個點多初始化了
Rectangle(Point one, Point two)
Rectangle(int x1, int y1, int x2, int y2)
int getArea()//計算面積的函數
};
3.函數的實現
Point :: Point()//無參數的構造方法,對xy初始化{x = 0;y = 0;
}
Point :: Point(int a, int b){x = a;y = b;
}
void Point ::setXY(int a, int b)
{x = a;y = b;
}
int Point :: getX()//得到x的方法
{return x;
}
int Point :: getY()//得到有的函數{return y;
}
};
Rectangle :: Rectangle(){};//類Point的無參構造函數已經對每個對象做初始化,這里不用對每個點做初始化了
Rectangle ::Rectangle(Point one, Point two)
{point1 = one;point4 = two;init();
}
Rectangle :: Rectangle(int x1, int y1, int x2, int y2){point1.setXY(x1, y1);point4.setXY(x2, y2);init();
}
void Rectangle :: init()//給另外兩個點做初始化的函數{point2.setXY(point4.getX(), point1.getY() );point3.setXY(point1.getX(), point4.getY() );
}
void Rectangle :: printPoint()//打印四個點的函數{ init();
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 Rectangle :: getArea()//計算面積的函數
{int height, width, area;height = point1.getY() - point3.getY();width = point1.getX() - point2.getX();area = height * width;if(area > 0)return area;elsereturn -area;
}};
void main()
{
Point *p1 = new Point (-15, 56), *p2 = new Point (89, -10);//定義兩個點
Rectangle *r1 = new Rectangle (*p1, *p2);//用兩個點做參數,聲明一個矩形對象r1
Rectangle *r2 = new Rectangle (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;
}