【问题标题】:overloading base class method in derived class在派生类中重载基类方法
【发布时间】:2013-05-30 12:15:45
【问题描述】:

我试图理解为什么以下代码无法编译,显然解决方案依赖于在派生类中明确声明对 method_A 的依赖。 请参考以下代码:

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)" 指定了错误数量的参数。

阻止派生类知道其基类正在实现它试图重载的方法的技术原因是什么? 我希望更好地了解编译器/链接器在这种情况下的行为方式。

【问题讨论】:

  • 你错过了virtual吗?
  • 不,我的意图是重载函数。如果我们没有对象继承,它会像: void method_A(int param, int param2); void method_A(int param);

标签: c++ oop overloading


【解决方案1】:

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

 myDerived.method_A(1,2);

为避免在 Derived 类中隐藏 Base 类方法,请像在 Derived2 类中一样使用 using 关键字。

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

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

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

【讨论】:

    【解决方案2】:

    好吧,对于你正在打电话的人

     myDerived.method_A(1,2);
    

    有 2 个参数,而在基类和派生类中,方法都被声明为只接受一个参数。

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

    【讨论】:

    • myDerived.method_A(1,2);应该调用基类方法。我同意,我想说超载
    【解决方案3】:

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

     virtual void method_A(int param, int param2)
    

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

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

    【讨论】:

    • 正如在其他 cmets 中所说,我实际上确实想超载
    猜你喜欢
    • 2013-05-18
    • 1970-01-01
    • 2014-10-17
    • 2012-11-10
    • 2014-12-23
    • 2017-04-03
    • 1970-01-01
    • 2014-09-05
    相关资源
    最近更新 更多