1

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

下面是我的编译器会发出(的mingw32-G ++代码:: Blocks的13.12里面)

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)。也不起作用。

+0

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

回答

1

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

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