继承中的函数覆盖

分俩种情况来考虑:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值