c++多态理解

#include <iostream>

using namespace std;

#define M_PI 3.144
class CFigure
{
public:
    virtual char* FigureType() = 0;
    virtual double Circumference() = 0;
    virtual double Area() = 0;
    virtual ~CFigure(){}
};

class CTriangle :public CFigure
{
public:
    CTriangle()
    {
        a = b = c = 0;
    }
    CTriangle(double a, double b, double c) :a(a), b(b), c(c) {}
    virtual char* FigureType()
    {
        return "Triangle";
    }
    virtual double Circumference()
    {
        return a + b + c;
    }
    virtual double Area()
    {
        double S = Circumference() / 2;
        return sqrt(S*(S - a)*(S - b)*(S - c));
    }
private:
    double a, b, c;
};

class CSquare :public CFigure
{
public:
    CSquare()
    {
        a = b = 0;
    }
    CSquare(double a, double b) :a(a), b(b) {}
    virtual char* FigureType()
    {
        return "Square";
    }
    virtual double Circumference()
    {
        return 2 * a + 2 * b;
    }
    virtual double Area()
    {
        return a*b;
    }
private:
    double a, b;
};

class CCircle :public CFigure
{
public:
    CCircle()
    {
        r = 0;
    }
    CCircle(double r) :r(r) {}
    virtual char* FigureType()
    {
        return "Circle";
    }
    virtual double Circumference()
    {
        return 2 * r*M_PI;
    }
    virtual double Area()
    {
        return r*r*M_PI;
    }
private:
    double r;
};

int main()
{
    CFigure* figures[3];

    figures[0] = new CTriangle(2.1, 3.2, 4.3);
    figures[1] = new CSquare(5.4, 6.5);
    figures[2] = new CCircle(8.8);

    for (int i = 0;i < 3;i++)
    {
        cout << "Figure type:\t" << figures[i]->FigureType()
            << "\nCircumference:\t" << figures[i]->Circumference()
            << "\nArea:\t" << figures[i]->Area()
            << endl << endl;
    }
    return 0;
}
结果:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值