在派生类中重载基类方法

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 方法同名的非虚方法时,它会将 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.

这篇关于在派生类中重载基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)