首页 > 代码库 > 第16章 多态性

第16章 多态性

/** ************重载,重写(覆盖),隐藏的识别*************重载:如何调用取决于参数覆盖:如何调用取决于object(有virtual 同名 同参)隐藏:如何调用取决于pointera、编译时多态性:通过重载函数实现 b、运行时多态性:通过虚函数实现。包含纯虚函数(virtual void funtion()=0 )的类称为抽象类。由于抽象类包含了没有定义的纯虚函数,所以不能定义抽象类的对象。小结:1、有virtual才可能发生多态现象2、不发生多态(无virtual)调用就按原类型调用*/#include<iostream>using namespace std;class Base{public:    virtual void f(float x)    {        cout<<"Base::f(float)"<< x <<endl;    }    void g(float x)    {        cout<<"Base::g(float)"<< x <<endl;    }    void h(float x)    {        cout<<"Base::h(float)"<< x <<endl;    }private:    float x;};class Derived : public Base{public:    virtual void f(float x)    {        cout<<"Derived::f(float)"<< x <<endl;   //多态(覆盖)必须不同类    }    void g(int x)    {        cout<<"Derived::g(int)"<< x <<endl;     //隐藏(参数不同。此时,不论有无virtual关键字,                                                //基类的函数将被隐藏(注意别与重载混淆)。)    }                                            //重载必须要在同一个类中定义    void h(float x)    {        cout<<"Derived::h(float)"<< x <<endl;   //隐藏(参数也相同,但是基类函数没有virtual关键字。    }                                            //此时,基类的函数被隐藏(注意别与覆盖混淆)。)};int main(void){    Derived d;    Base *pb = &d;    Derived *pd = &d;    // Good : behavior depends solely on type of the object    pb->f(3.14f);   // Derived::f(float) 3.14    pd->f(3.14f);   // Derived::f(float) 3.14    // Bad : behavior depends on type of the pointer    pb->g(3.14f);   // Base::g(float)  3.14    pd->g(3.14f);   // Derived::g(int) 3     // Bad : behavior depends on type of the pointer    pb->h(3.14f);   // Base::h(float) 3.14    pd->h(3.14f);   // Derived::h(float) 3.14    return 0;}