重载基类方法在派生类中 [英] overloading base class method in derived class
问题描述
我试图理解为什么下面的代码不能编译,显然解决方案依赖于在派生类中明确声明对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方法同名的非虚方法时,它会隐藏Derived类中的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);
为避免在Derived类中隐藏Base 类方法,请使用关键字
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);
Check out this for better explanation why name hiding came into picture.
这篇关于重载基类方法在派生类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!