标签:
C++中类与类之间存在着两种名称遮盖关系,变量遮盖、函数遮盖。其本质都是名字的查找方式导致的,当编译器要找一个名字,它一旦找到一个相符的名字,就不会往下找了,因此遮掩本质上是优先查找那个名字的问题。
//:采用using声明,使查找范围扩大至父类指定的函数:
class Base
{
public:
void CommonFunction(){cout << "Base::CommonFunction()" << endl;}
void virtual VirtualFunction(){cout << "Base::VirturalFunction()" << endl;}
void virtual VirtualFunction(int x){cout << "Base::VirtualFunction() With Parms" << endl;}
void virtual PureVirtualFunction() = 0;
};
class Derived: public Base
{
public:
using Base::VirtualFunction; // 第一级查找也要包括Base::VirtualFunction
void CommonFunction(){cout << "Derived::CommonFunction()" << endl;}
void virtual VirtualFunction(){cout << "Derived::VirturalFunction()" << endl;}
void virtual PureVirtualFunction(){cout << "Derived::PureVirtualFunction()" << endl;}
};
int main()
{
Derived d;
d.VirtualFunction(3); // 这样没问题了,编译器会把父类作用域里面的函数名VirtualFunciton也纳入第一批查找范围,这样就能发现其实是父类的函数与main中的调用匹配得更好(因为有一个形参),这样会输出Base::VirtualFunction() With Parms
return 0;
}
//:使用转交函数强制指定父类的作用域
class Base
{
public:
void CommonFunction(){cout << "Base::CommonFunction()" << endl;}
void virtual VirtualFunction(){cout << "Base::VirturalFunction()" << endl;}
void virtual VirtualFunction(int x){cout << "Base::VirtualFunction() With Parms" << endl;}
void virtual PureVirtualFunction() = 0;
};
class Derived: public Base
{
public:
using Base::VirtualFunction;
void CommonFunction(){cout << "Derived::CommonFunction()" << endl;}
void virtual VirtualFunction(){cout << "Derived::VirturalFunction()" << endl;}
void virtual PureVirtualFunction(int x){cout << "Derived::PureVirtualFunction()" << endl;}
void virtual VirtualFunction(int x){Base::VirtualFunction(x)};
};
int main()
{
Derived d;
d.VirtualFunction(3); // 输出Base::VirtualFunction() With Parms
return 0;
}
标签:
原文地址:http://www.cnblogs.com/chengkeke/p/5417380.html