c++多态例子

2021-08-13  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读