函数覆盖不同的返回类型 [英] function overriding with different return types

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

问题描述

返回类型是否影响函数覆盖? (就我所知,return typde不是函数/方法签名的一部分)
在一个基类中,我有一个函数,它没有获取参数,返回 int 并且是纯虚拟的。在每个派生类中,我为返回类型定义一个枚举。在派生类中重写该函数,即它具有相同的签名但行为不同。
问题是:是否合法的覆盖和返回类型不是函数覆盖的一部分

Does the return type influence on function overriding? (As far as I know return typde is not a part of a function/method signature) In a base class I have a function, which doesn't get arguments, returns int and is pure virtual. In each derived class, I define an enum for the return type.The function is overridden in the derived classes, i.e. it has the same signature but different behavior. The question is: Is that legal for overriding and return type is not a part of function overriding?

代码示例: / p>

Code example:

class Base
{
  public:
  typedef int ret;
  virtual ret method() = 0;
};

class Der1
{
public:
  enum ret1{
    ret1_0,
    ret1_1
  };
  ret1 method() { return ret1_1;}
};

class Der1
{
public:
  enum ret2{
    ret2_0,
    ret2_1
  };
  ret1 method() { return ret2_0;}
};


推荐答案

您可以覆盖具有不同返回类型的函数, strong> 协变返回类型

You can override functions with different return types but only covariant return types are allowed.

函数覆盖意味着在运行时将调用Base类方法或Derived类方法,具体取决于指针指向的实际对象。

它意味着:

ie:可以调用Base类方法的每个地方都可以通过调用Derived类方法来代替,而不会对调用代码进行任何更改。

Function Overriding 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 so the Standard enforces this condition.

没有此条件,现有代码将通过添加新功能(新重写功能)而中断。

Without this condition the existing code will break by addition of new functionality(new overriding functions).

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

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