C++ : 多态性

多态实现方式有两种:虚函数、多态性
1.虚函数实现

#include <iostream>
using namespace std;
class Shape
{
    public:
        Shape(int a=0, int b=0){
            width = a; height = b;
        }
        virtual int area(){
            cout << "Parent class area :" <<endl;
            return 0;
        }
    protected:
        int width, height;
};
class Rectangle: public Shape
{
    public:
        Rectangle(int a=0, int b=0):Shape(a, b) { }
        int area(){
            cout << "Rectangle class area :" <<endl;
            return (width * height); 
        }
};
class Triangle: public Shape
{
    public:
        Triangle(int a=0, int b=0):Shape(a, b){ }
        int area(){
            cout << "Triangle class area :" <<endl;
            return (width * height / 2); 
        }
};

int main()
{
    Rectangle rec(10,7);
    Triangle tri(10,5);

    Shape *shape;
    shape = &rec;    // 存储矩形的地址
    shape->area();   // 调用矩形的求面积函数 area

    shape = &tri;    // 存储三角形的地址
    shape->area();   // 调用三角形的求面积函数 area
    return 0;
}

2.抽象类 (纯虚函数)

#include <iostream>
using namespace std;
class Shape 
{
    public:
        virtual int area() = 0;        // 提供接口框架的纯虚函数
        void setWidth(int w)
        { width = w; }
        void setHeight(int h)
        { height = h; }
    protected:
        int width; int height;
};
class Rectangle: public Shape
{
    public:
        int area()
        { return (width * height); }
};
class Triangle: public Shape
{
    public:
        int area()
        { return (width * height)/2; }
};
int main(void)
{
   Rectangle Rect;
   Triangle  Tri;
 
   Rect.setWidth(5);
   Rect.setHeight(7);
   cout << "Total Rectangle area: " << Rect.area() << endl;

   Tri.setWidth(5);
   Tri.setHeight(7);
   cout << "Total Triangle area: " << Tri.area() << endl;

   return 0;
}
发布了25 篇原创文章 · 获赞 2 · 访问量 817

猜你喜欢

转载自blog.csdn.net/yangjinjingbj/article/details/104056456