继承中的函数覆盖

来源:互联网 发布:淘宝如何开直通车省钱 编辑:程序博客网 时间:2024/06/05 19:35

分俩种情况来考虑:

1,虚函数。

          只用函数在基类中被声明为虚函数,那么任何通过基类类型的指针对该函数的调用都是合法的,至于调用的是基类中还是派生类中的函数,则依具体情况。

               举例: class Base{

                           public:

                                     virtual int fcn();

                           };

                           class D1:public Base{

                           public:

                                    //hides fcn in the base;this fcn is not virtual

                                    int fcn(int);        //parameter list differs from fan in Base

                                    //D1 inherits definition of Base::fcn()

                            };

                            class D2:public D1{

                            public:

                                     int fcn(int);        //nonvirtual function hides D1::fcn(int)

                                     int fcn();            //redefines virtual fan from Base

                            };

 

                           Base bobj;  D1 d1obj;   D2 d2obj;

                           Base *bp1 = &bobj,  *bp2 = &d1obj,  *bp3 = &d2obj;

                           bp1->fun();           //ok:virtual call,will call Base::fcn at run time

                           bp2->fun();           //ok:virtual call,will call Base::fcn at run time

                           bp3->fun();           //ok:virtual call,will call D2::fcn at run time

       

2,非虚函数。

          在基类和派生类中使用同一名字的成员函数,其行为与数据成员一样:在派生类作用域中派生类成员将屏蔽基类成员。即使函数原型不同,基类成员也会被屏蔽。

               举例:class Base{

                               int memfun();

                           };

                           class Derived : public Base{

                                    int memfun(int);       //hides memfun in the base

                           };

 

                           Derived d;   Base b;

                           b.memfcn();                   //calls Base::memfcn

                           d.memfcn(10);               //calls Derived::memfun

                           d.memfcn();                   //error:memfcn with no arguments is hidden

                           d.Base::memfcn();         //ok:calls Base::memfcn

原创粉丝点击