https://www.jb51.net/article/117380.htm
函數的覆蓋
?? 覆蓋發生的條件:
(1) 基類必須是虛函數(使用virtual 關鍵字來進行聲明)
(2)發生覆蓋的兩個函數分別位于派生類和基類
(3)函數名和參數列表必須完全相同
函數的隱藏
??? 隱藏發生的條件:
(1)子類和父類的函數名相同,參數列表可以不一樣
看完下面的例子就明白了
#include "iostream"
using namespace std;
class CBase{ public: virtual void xfn(int i){ cout << "Base::xfn(int i)" << endl; //1 } void yfn(float f){ cout << "Base::yfn(float)" << endl; //2 } void zfn(){ cout << "Base::zfn()" << endl; //3 }
};
class CDerived : public CBase{ public: void xfn(int i){ cout << "Derived::xfn(int i)" << endl; //4 } void yfn(int c){ cout << "Derived:yfn(int c)" << endl; //5 } void zfn(){ cout << "Derived:zfn()" << endl; //6 }
};
void main(){ CDerived d; CBase *pb = &d; CDerived *pd = &d; pb->xfn(5); //覆蓋 pd->xfn(5); //直接調用 pb->yfn(3.14f); //直接調用 pd->yfn(3.14f); //隱藏 pb->zfn(); //直接調用 pd->zfn(); //隱藏
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!