C++ 多态

来源:互联网 发布:农村淘宝的规划 编辑:程序博客网 时间:2024/05/22 04:33

说起多态,首先想起的肯定是虚函数 virtual

先看看一个实例:

/*多态*/#include <iostream>using namespace std;class Shape{public:    Shape(int x,int y):m_x(x),m_y(y){}    void Draw(){        cout<<"("<<m_x<<","<<m_y<<")"<<endl;    }   public:    int m_x;    int m_y;};class Rect:public Shape{public:    Rect(int x,int y,int wid,int high):Shape(x,y),m_wid(wid),m_high(high){}    void Draw(){        cout<<"矩形("<<m_x<<","<<m_y<<","<<m_wid<<","<<m_high<<")"<<endl;    }   public:    int m_wid;    int m_high;};class Circle:public Shape{public:    Circle(int x,int y,int r):Shape(x,y),m_r(r){}    void Draw(){        cout<<"圆("<<m_x<<","<<m_y<<","<<m_r<<endl;    }   public:    int m_r;};int main(void){    Shape shape(8,9);//  Rect *pRect = &shape; // 需要转换    Rect *pRect = static_cast<Rect*>(&shape);    pRect->Draw();    return 0;}

执行的结果:矩形(8,9,4197207,0)

将main()中的改为

 Shape*pShap = &rect; pShap->Draw();

执行的结果:(1,2)

结论:通过指向子类对象的基类指针调用函数,最终被调用的是基类中的函数;

            通过指向基类对象的子类指针调用函数,最终被调用的是子类中的函数,但是所有子类所特有的成员变量值不确定.(需要避免)

            通过指向子类对象的基类指针调用子类所独有的函数,会导致编译错误

 

二、虚函数和多态

 

原创粉丝点击