【问题标题】:Simultaneous overriding and overloading in C++在 C++ 中同时覆盖和重载
【发布时间】:2017-05-06 11:09:19
【问题描述】:

大家好,我对下面这段 C++ 代码感到困惑,其中重载和覆盖在某种程度上是同时发生的。

这是我的编译器给出的错误(Code::Blocks 13.12 中的mingw32-g++)

error: no matching function for call to 'Derived::show()'
note:  candidate is:
note:  void Derived::show(int)
note:  candidate expects 1 argument, 0 provided

这是生成它们的代码。

    #include <iostream>
    using namespace std;

    class Base{
    public:
      void show(int x){
        cout<<"Method show in base class."<<endl;
      }
      void show(){
        cout<<"Overloaded method show in base class."<<endl;
      }
    };

    class Derived:public Base{
    public:
      void show(int x){
        cout<<"Method show in derived class."<<endl;
      }
    };

    int main(){
      Derived d;
      d.show();
    }

我试图将 Base::show() 声明为虚拟。然后我对 Base::show(int) 进行了同样的尝试。也不行。

【问题讨论】:

  • 查找“隐藏规则”。你的编译器正在做它需要做的事情。

标签: c++ inheritance overloading overriding overload-resolution


【解决方案1】:

这是隐藏名称。 Derived::show 隐藏Base 中的同名方法。您可以通过using介绍他们。

class Derived:public Base{
public:
  using Base::show;
  void show(int x){
    cout<<"Method show in derived class."<<endl;
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多