1. 程式人生 > >YTUOJ——矩形類定義【C++】

YTUOJ——矩形類定義【C++】

題目描述

定義一個矩形類,資料成員包括左下角和右上角座標,定義的成員函式包括必要的建構函式、輸入座標的函式,以及計算並輸出矩形面積的函式。要求使用提示中給出的測試函式並不得改動。

輸入

四個數,分別表示矩形左下角和右上角頂點的座標,如輸入3.7 0.4 6.5 4.9,代表左下角座標為(3.7, 0.4),右上角座標為(6.5, 4.9)。

輸出

輸出一共有3行(請參考提示(hint)中的main函式): 第一行:由輸入的座標確定的矩形物件p1的面積 第二行:由物件複製得到的矩形物件p2的面積 第三行:直接初始化得到的矩形物件p3的面積

樣例輸入

3.7 0.4 6.5 4.9

樣例輸出

12.6 12.6 10

提示

int main()
{
    Rectangle p1;
    p1.input();
    p1.output();
    Rectangle p2(p1);
    p2.output();
    Rectangle p3(1,1,6,3);
    p3.output();
    return 0;
}

答案

#include "iostream"
using namespace std;

class Rectangle{
public:
    Rectangle();
    Rectangle (const Rectangle&p);
    Rectangle(double ,double ,double ,double);
    void input(){  
	cin>>x1>>y1>>x2>>y2;
    }  
    void output(){  
	cout<<(x2-x1)*(y2-y1)<<endl;  
    }  
private:
    double x1,x2,y1,y2;
    double s;
};
 
Rectangle::Rectangle(const Rectangle&p){
    x1=p.x1;
    y1=p.y1;
    x2=p.x2;
    y2=p.y2;
}
Rectangle::Rectangle(double a,double b,double c,double d)
{
    x1=a;
    y1=b;
    x2=c;
    y2=d;
}
Rectangle::Rectangle(){
    x1=0;
    y1=0;
    x2=0;
    y2=0;
}

int main()
{
    Rectangle p1;
    p1.input();
    p1.output();
    Rectangle p2(p1);
    p2.output();
    Rectangle p3(1,1,6,3);
    p3.output();
    return 0;
}