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

#include <cstdio>
#include <cmath>
#include <iostream>
//用DB代替double,以后可以直接用double声明
#define DB double
//定义PI
#define PI 3.1415926
using 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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值