名称遮掩
int x = 20; void someFunc() { double x = 10.0; std::cout << x; ]
如上操作,函数打印结果是10.0还是20呢?是10.0。因为代码访问顺序是这样的,当需要变量x,现在someFun()函数里找,找不到x,再全局找x。本例:double x遮掩了int x
继承中的名称遮掩
Derived类的调用作用域顺序
class Base { public: virtual void mf2(); }; class Derived :public Base { public: void mf4(){ fm2(); //调用基类中的fm2 } };
mf4()再函数内查找fm2----在Derived类查找fm2()------ 在Base类查找mf2()
- 隐藏基类函数的情形
#include <iostream> class Base { private: int x; public: virtual void mf1() = 0; virtual void mf1(int); virtual void mf2(); void mf3(); void mf3(double); }; class Derived :public Base { public: virtual void mf1(); void mf3(); void mf4(); }; int main() { Derived d; int x = 10; d.mf1(); //正确 d.mf1(x); //错误,Base::fm1(int)被隐藏了 d.mf2(); //正确 d.mf3(); //正确 d.mf3(x); //错误,Base::mf3(double)被隐藏了 return 0; }
- 可在Derived类加上using Base, 让Base类的作用函数对Derived类可见,不再隐藏
class Derived :public Base { public: using Base::mf1; using Base::mf3; //取消隐藏 virtual void mf1(); void mf3(); void mf4(); };
- 也可以通过在Derived类调用Base类的函数--避免隐藏Basse类的函数
#include <iostream> class Base { public: void mf1(int a) { printf("====%d\n ",a ); }; }; class Derived :public Base { public: void mf1() { Base::mf1(10); }; }; int main() { Derived d; d.mf1(); //正确 return 0; }