覆盖具有不同返回类型的成员函数 [英] Override a member function with different return type

查看:168
本文介绍了覆盖具有不同返回类型的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

#include <iostream>

using namespace std;

class base
{
   public:
      virtual int func()
      {
         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()
{
   base *bptr = new derived;
   bptr->func();

   return 0;
}

编译器给出上述代码的错误,覆盖函数。为什么不能用不同的返回类型覆盖派生类中的函数?

The compiler gives an error for the above code that there is conflicting type for the overriden function. Why is it not possible to override a function in the derived class with a different return type ?

我相信,为了覆盖一个函数,基类virtual method需要在派生类中重新定义。要重新定义方法,方法的签名必须相同。因为返回类型不是签名的一部分,我相信即使返回类型有差异,方法仍然会被重新定义?在这种情况下,对于上面的代码,虚函数 func 在具有不同返回类型的派生类中被重新定义。但是编译器抛出一个错误。我的理解是否正确?

I believe, in-order to override a function, the base class virtual method needs to be redefined in the derived class. To redefine a method, the signatures of the methods has to be the same. Since return type is not part of the signature, i believe even if there is difference in return type, the method will still be redefined? In that case for the code above, virtual function func is redefined in the derived class with a different return type. But the compiler throws an error. Is my understanding correct?

推荐答案

重写实质上意味着Base类方法或Derived类方法将在run-时间,取决于指针指向的实际对象。

这意味着:

ie:可以调用Base类方法的每个地方都可以通过调用Derived类方法没有任何改变调用代码。

Overriding essentially means that either the Base class method or the Derived class method will be called at run-time depending on the actual object pointed by the pointer.
It implies that:
i.e: Every place where the Base class method can be called can be replaced by call to Derived class method without any change to calling code.

为了实现这一点,唯一可能的方法是限制重写的虚方法的返回类型返回与Base类相同的类型或从(共变异返回类型),并且标准强制执行此条件。

In order to achieve this the only possible way is to restrict the return types of the overriding virtual methods to return the same type as the Base class or a type derived from that(co-variant return types) and the Standard enforces this condition.

如果上述条件不成立,将会留下一个窗口,通过添加新功能来打破现有代码。

If the above condition was not in place it would leave a window to break the existing code by addition of new functionality.

这篇关于覆盖具有不同返回类型的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆