#include<iostream> using namespace std; class B { public: void f(int x) {cout<<"B::f(int)"<<endl;} void f(float x) {cout<<"B::f(float)"<<endl;} virtual void g(void) {cout<<"B::g(void)"<<endl;} }; class D : public B { public: virtual void g(void) {cout<<"D::g(void)"<<endl;} }; int main() { D d; B *pb = &d; pb->f(3.14f);//B::f(float) pb->f(42);//B::f(int) pb->g();//D::g(void) return 0; }
/*
*隐藏:
*1.派生类的函数与基类函数同名,但参数不同。此时不论
* 有无virtual关键字基类函数将被隐藏
*2.派生类函数与基类函数同名同参,但基类没有virtual
* 关键字。基类函数将被隐藏
*/
#include<iostream> using namespace std; class B { public: virtual void f(float x) {cout<<"B::f(float)"<<endl;} void g(float x) {cout<<"B::g(float)"<<endl;} void h(float x) {cout<<"B::h(float)"<<endl;} }; class D : public B { public: virtual void f(float x) {cout<<"D::f(float)"<<endl;} void g(float x) {cout<<"D::g(float)"<<endl;} void h(float x) {cout<<"D::h(float)"<<endl;} }; int main() { D d; B *pb = &d; D *pd = &d; pb->f(3.14f);//D::f(float)//覆盖 pd->f(3.14f);//D::f(float) pb->g(3.14f);//B::g(float) pd->g(3.14f);//D::g(float)//隐藏 pb->h(3.14f);//B::h(float) pd->h(3.14f);//D::h(float)//隐藏 return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/chenmengmengx/article/details/46754389