【问题标题】:Whats wrong with the following code? It's not compiling以下代码有什么问题?它没有编译
【发布时间】:2011-03-17 16:22:58
【问题描述】:
#include <iostream> 
#include <vector>
using namespace std;

class Base
{
public:
      void Display( void )
      {
            cout<<"Base display"<<endl;
      }

      int Display( int a )
      {
            cout<<"Base int display"<<endl;
            return 0;
      }

};

class Derived : public Base
{
public:

      void Display( void )
      {
            cout<<"Derived display"<<endl;
      }
};


void main()
{
   Derived obj;
   obj.Display();  
   obj.Display( 10 );
}

$test1.cpp: In function ‘int main()’:  
test1.cpp:35: error: no matching function for call to ‘Derived::Display(int)’  
test1.cpp:24: note: candidates are: void Derived::Display()

在注释掉 obj.Display(10) 时,它可以工作。

【问题讨论】:

  • 你用的是什么编译器?它看起来像gcc,但这是最新的代码吗?为什么即使您已将 main 定义为 void main() ,您也会得到 $test1.cpp: In function ‘int main()’:
  • 尝试使用 gcc 和 vc++。从 vc++ 编辑器复制代码,粘贴 gcc 输出。

标签: c++


【解决方案1】:

您需要使用using 声明。 X 类中名为 f 的成员函数隐藏 X 的基类中名为 f 的所有其他成员。

为什么?

阅读 AndreyT 的 this explanation

您可以使用using 声明来引入这些隐藏名称:

using Base::Display 是您需要包含在派生类中的内容。

此外,void main() 是非标准的。使用int main()

【讨论】:

  • 他将 main 定义为void main(),但他怎么得到$test1.cpp: In function ‘int main()’:
  • @Muggen:将main 声明为具有int 以外的任何返回类型是非法的。这个特定的实现似乎只是忽略了这个错误并将代码视为正确地声明了main
【解决方案2】:

你需要放置 -

using Base::Display ; // in Derived class

如果Derived 类中的方法名称匹配,编译器将不会查看Base 类。因此,为避免这种行为,请放置using Base::Display;。如果有任何方法实际上可以将int 作为Display 的参数,那么编译器将查看Base 类。

class Derived : public Base
{
    public:
    using Base::Display ;
    void Display( void )
    {
        cout<<"Derived display"<<endl;
    }
};

【讨论】:

  • 这是编译器特有的吗?
  • 它适用于使用。你能解释一下没有使用会发生什么吗?
  • 不应将 int Display(int) 派生出来,因为它已被声明为 public。
  • @Gunner : 它被派生但隐藏在派生类中。
  • @Gunner :出于历史原因。阅读我的答案。
【解决方案3】:

您通过在派生类中创建具有相同名称的函数来屏蔽原始函数定义:http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.8

【讨论】:

    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多