1601 优雅地写出C++代码 5-12

来源:互联网 发布:谁的行书比较好练 知乎 编辑:程序博客网 时间:2024/06/03 18:27
#include <cstdio>#include <cmath>#include <iostream>
//用DB代替double,以后可以直接用double声明#define DB double
//定义PI#define PI 3.1415926using namespace std;
//Shape类,基类class Shape{public:    Shape(DB x, DB y)    {        X=x, Y=y;    }    ~Shape(){};    void SetX(DB x)    {        X=x;    }    void SetY(DB y)    {        Y=y;    }    DB GetX(){return X;}    DB GetY(){return Y;}private:    DB X;    DB Y;};class Rectangle:public Shape               //由Shape类派生出Rectangle类{public:    Rectangle(DB x,DB y,DB a,DB b):Shape(x,y){X2=a,Y2=b;}      //参数x,y传递给Shape,另外两个参数只能自己在类私有保存了    ~Rectangle(){}    DB GetArea()    {        return (X2-GetX())*(Y2-GetY());                        //X2,Y2可直接读取,但Shape类中的X,Y是私有的,只能用GetX方法    }    DB GetPeri()    {        return 2*(X2-GetX())+2*(Y2-GetY());    }    DB GetX2(){return X2;}    DB GetY2(){return Y2;}private:    DB X2;    DB Y2;};class Circle:public Shape{public:    Circle(DB x,DB y,DB r):Shape(x,y){R=r;}    ~Circle(){}    DB GetArea()    {        return PI*R*R;    }    DB GetPeri()    {        return 2*PI*R;    }private:    DB R;};class Square:public Rectangle{public:    Square(DB x,DB y,DB a,DB b):Rectangle(x,y,a,b)    {        if((a-x)!=(b-y))        {            cout<<"Opps!It's not a square TAT"<<endl;                 //判断是否为正方形            square = false;        }        else            square = true;    }    ~Square(){}    DB GetArea()    {        if(square){return (GetX()-GetX2())*(GetX()-GetX2());}        cout<<"There must be something wrong!"<<endl;    }    DB GetPeri()    {        if(square){return 4*abs(GetX()-GetX2());}        cout<<"There must be something wrong!"<<endl;    }private:    bool square;};int main(){    return 0;}


 

0 0
原创粉丝点击