-1

我在玩c++规则。我遇到了一个错误,但我无法解释。请帮助解释为什么会发生编译错误。顺便说一句,我对解决这个问题并不感兴趣。谢谢

Q1 为什么名称隐藏在这种情况下不起作用?例如,如果我们删除 lineA 的关键字 virtual。编译将起作用

Q2在case2中添加一个函数后,编译通过。

请帮助解释 Q1 和 Q2。

#包括

using namespace std;

class base
{
   public:
      virtual int func() // lineA
      {
         cout << "vfunc in base class\n";
         return 0;
      }
};

class derived: public base
{
   public:
      double func()
      {
         cout << "vfunc in derived class\n";
         return 0;
      }
};

int main()
{
   return 0;
}

输出:

main.cpp:18:14: error: conflicting return type specified for 'virtual double derived::func()'
       double func()
              ^
main.cpp:8:19: error:   overriding 'virtual int base::func()'
       virtual int func()

案例2:

#include <iostream>

using namespace std;

class base
{
   public:
      virtual int func()
      {
         cout << "vfunc in base class\n";
         return 0;
      }
     // new added 
      virtual double func(int)
      {
          return 0.0;
      }
};

class derived: public base
{
   public:
      double func(int)
      {
         cout << "vfunc in derived class\n";
         return 0;
      }
};

int main()
{
   return 0;
}             ^
4

2 回答 2

0

当你重写一个函数时,你的新实现必须在原来的时候是可调用的。这里的base函数返回一个int. 这意味着任何调用者都会期望一个int.

发生错误是因为您的覆盖函数返回的是 adouble而不是int.

于 2014-01-28T23:03:24.903 回答
0

Well as the compiler error states you have defined different return types for func(). You may think that this should be handeled by C++ overloading, but overloading can only be done on input parameters not on return values. For example:

class base
{
   public:
      virtual int func(int param)
      {
         cout << "vfunc in base class\n";
         return 0;
      }
};

class derived: public base
{
   public:
      double func(double param)
      {
         cout << "vfunc in derived class\n";
         return 0;
      }
};

In this code func is overloaded in derived since it has another type for the input param.

于 2014-01-28T23:05:16.110 回答