31

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) 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.

4

3 回答 3

47

它称为名称隐藏。当您定义与 Base 方法同名的非虚拟方法时,它会在 Derived 类中隐藏 Base 类方法,因此您会收到错误

 myDerived.method_A(1,2);

为了避免在 Derived 类中隐藏基类方法,请使用 using 关键字,就像在 Derived2 类中所做的那样。

此外,如果你想让它工作,你可以明确地做到这一点

myDerived.Base::method_A(1,2);

查看内容以获得更好的解释为什么名称隐藏会出现。

于 2013-05-30T13:33:13.053 回答
0

好吧,对于一个你打电话的人

 myDerived.method_A(1,2);

带有 2 个参数,而在基类和派生类中,该方法都被声明为仅采用一个参数。

其次,你没有覆盖任何东西,因为 method_A 不是虚拟的。你超载了。

于 2013-05-30T12:18:00.963 回答
-1

如果您的意图是覆盖voidBase::method_A(int param, int param2)那么您应该在基类中将其标记为虚拟:

 virtual void method_A(int param, int param2)

任何重写 this 的函数都必须具有相同的参数和几乎相同的返回类型(“几乎”松散地意味着不同的返回类型必须是多态相关的,但在大多数情况下它应该具有相同的返回类型)。

您当前所做的只是重载基类中的函数。关键字是将using基类函数带入子类的命名空间,因为默认情况下语言行为不这样做。

于 2013-05-30T12:20:39.410 回答