关于C++多态的一个例子

本文详细介绍了面向对象编程的基本概念及其在C++中的应用,特别关注了多态性的原理和实践。通过具体示例,展示了如何使用C++实现继承、多态和封装等面向对象特性,旨在帮助开发者深入理解并有效运用这些关键概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cmath>

using namespace std;

class Shape
{
    public:
        Shape() {}
        virtual ~Shape() = 0;
        virtual double getPerimeter() = 0;
        virtual double getArea() = 0;
};

Shape::~Shape() { }    //①能不能不写??为什么??

class Triangle: public Shape
{
    public:
        Triangle() {}
        Triangle(double a, double b, double c):a(a),b(b),c(c) {}
        //Triangle(const Triangle &copy):a(copy.a),b(copy.b),c(copy.c) {}
        Triangle& operator=(const Triangle& assign)
        {
            if (this != &assign)
            {
                a = assign.a;
                b = assign.b;
                c = assign.c;
            }
            return *this;
        }
        virtual ~Triangle() {}
       
        virtual double getPerimeter()
        {
            return a+b+c;
        }
        virtual double getArea()
        {
            double q = (a+b+c)/2;
            return sqrt(q*(q-a)*(q-b)*(q-c));
        }
    private:
        double a;
        double b;
        double c;
};

class Rectangle:public Shape
{
    public:
        Rectangle() {}
        Rectangle(double h,double w):height(h),width(w) //②调换顺序,如何??
        { }
        virtual ~Rectangle() {}
       
        virtual double getPerimeter()
        {
            return 2 * (width + height);
        }
       
        virtual double getArea()
        {
            return width * height;                    //③假如Rectangle有一个独有的成员函数,问如何利用动态绑定技术实现??
        }
    private:
        double height;
        double width;
};

int main()
{
    Shape *shape[2];
    shape[1] = new Rectangle(1.0, 2.0);
    shape[0] = new Triangle(3.0, 4.0, 5.0);
   
    for (int i = 0; i < 2; ++i)
    {
        if (typeid(*shape[i]) == typeid(Triangle))   //④typeid用法??
            cout << "这是一个三角形" << endl;
        else if (typeid(*shape[i]) == typeid(Rectangle))
            cout << "这是一个矩形" << endl;
        cout << "周长为:" << shape[i]->getPerimeter() << " ";
        cout << "面积为:" << shape[i]->getArea() << endl;
    }
   
    delete shape[0];
    delete shape[1];
    return EXIT_SUCCESS;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值