设计一个点类point,再设计一个矩形类,矩形类使用point类的两个坐标点作为矩形的对角顶点,并可以输出4个坐标值和面积。使用测试程序验证程序。

源程序:

//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<<" 矩形 r2 的 4 个定点坐标:"<< endl;

  r2.printPoint();

  cout<<"矩形 r2 的面积:"<< r2.getArea() << endl;

}

 运行结果:

原文地址:https://www.cnblogs.com/duanqibo/p/11889119.html