在派生类中重载基类方法
我试图理解为什么以下代码无法编译,显然该解决方案依赖于在派生类中专门声明对 method_A 的依赖.请参考以下代码:
I am trying to understand why the following code does not compile, apparently the solution relies in specifically declaring the dependency on method_A in the derived class. Please refer to the following code:
class Base
{
public:
void method_A(int param, int param2)
{
std::cout << "Base call A" << std::endl;
}
};
//does not compile
class Derived : public Base
{
public:
void method_A(int param)
{
std::cout << "Derived call A" << std::endl;
}
};
//compiles
class Derived2 : public Base
{
public:
using Base::method_A; //compile
void method_A(int param)
{
std::cout << "Derived call A" << std::endl;
}
};
int main ()
{
Derived myDerived;
myDerived.method_A(1);
myDerived.method_A(1,2);
Derived2 myDerived2;
myDerived2.method_A(1);
myDerived2.method_A(1,2);
return 0;
}
"test.cpp", (S) 为 "Derived::method_A(int)" 指定了错误数量的参数.
"test.cpp", (S) The wrong number of arguments have been specified for "Derived::method_A(int)".
阻止派生类知道其基类正在实现它试图重载的方法的技术原因是什么?我希望更好地理解编译器/链接器在这种情况下的行为.
What is the technical reason that prevents the derived class to know its base class is implementing the method it's trying to overload? I am looking in understanding better how the compiler/linker behaves in this case.
推荐答案
它叫做名称隐藏.当你定义一个与 Base 方法同名的非虚方法时,它会将 Base 类方法隐藏在派生类,因此您收到错误
Its called Name Hiding. When you define a non virtual method with the same name as Base method it hides the Base class method in Derived class so you are getting the error for
myDerived.method_A(1,2);
为了避免在派生类中隐藏基类类方法,请像在派生2类中那样使用关键字.
To avoid hiding of Base class methods in Derived class use using keyword as you did in Derived2 class.
另外,如果你想让它工作,你可以明确地做到
Also if you want to make it work you can do it explictly
myDerived.Base::method_A(1,2);
查看 this 以更好地解释为什么隐藏姓名.
Check out this for better explanation why name hiding came into picture.
相关文章