美文网首页
c++多态例子

c++多态例子

作者: 一路向后 | 来源:发表于2021-08-13 21:29 被阅读0次

    1.源码实现

    #include <iostream>
    
    using namespace std;
    
    class Shape {
    public:
        Shape(int a, int b)
        {
            width = a;
            height = b;
        }
    
        /*int area()
        {
            cout << "Parent class area: " << endl;
            return 0;
        }*/
        virtual int area() = 0;
    
    protected:
        int width;
        int height;
    };
    
    class Rectangle : public Shape {
    public:
        Rectangle(int a, int b) : Shape(a, b){}
        int area()
        {
            cout << "Rectangle class area: " << width * height << endl;
            return width * height;
        }
    };
    
    class Triangle : public Shape {
    public:
        Triangle(int a, int b) : Shape(a, b){}
        int area()
        {
            cout << "Triangle class area: " << width * height / 2 << endl;
            return width * height / 2;
        }
    };
    
    int main()
    {
        Shape *shape;
        Rectangle rec(10, 7);
        Triangle tri(10, 5);
    
        shape = &rec;
    
        //调用矩形的求面积函数
        shape->area();
    
        shape = &tri;
    
        //调用三角形的求面积函数
        shape->area();
    
        return 0;
    }
    

    2.编译源码

    $ g++ -o example example.cpp
    

    3.运行及其结果

    $ ./example
    Rectangle class area: 70
    Triangle class area: 25
    

    相关文章

      网友评论

          本文标题:c++多态例子

          本文链接:https://www.haomeiwen.com/subject/rqbjbltx.html