条款50: 提高对C++的认识
class Base { public: virtual void f(int x); }; class Derived: public Base { public: virtual void f(double *pd); }; Derived *pd = new Derived; pd->f(10); // 错误!名字查找先于类型检查,现在derived类中找到f函数,然后进行类型检查,报错
问题在于Derived::f隐藏了Base::f,即使它们取的是不同的参数类型;所以编译器要求对f的调用取一个double*,而10这个数字当然不行。
如果想让Derived的用户可以访问Base::f,可以很容易地通过一个using声明来完成:
class Derived: public Base { public: using Base::f; // 将Base::f引入到 // Derived的空间范围 virtual void f(double *pd); }; Derived *pd = new Derived; pd->f(10); // 正确,调用Base::f