C ++:没有指针的协变返回类型 [英] C++ : Covariant return type without pointer

查看:98
本文介绍了C ++:没有指针的协变返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过继承创建了两个简单的类,并在子类中添加了虚函数和重写.

  class父类{上市:虚拟父母foo();};班级儿童:公共父母{上市:子foo()覆盖;}; 

在这种情况下,我的重写函数遇到错误:错误C2555:'Child :: foo':重写虚拟函数返回类型与'Parent :: foo'互不相同

如果我使用指针更改返回类型:

  class父类{上市:虚拟父母* foo();};班级儿童:公共父母{上市:Child * foo()覆盖;}; 

错误消失了!我不明白为什么必须使用指针来完成返回类型的协方差,而不能使用值类型或引用.一些网站或论坛解释说,由于返回的值是该函数中使用的值的副本,因此编译器知道指针的常量大小,但必须为覆盖的函数和父函数指示不同的大小,这显然是不可能的.

那么,为什么在这种情况下我不能使用除指针以外的任何东西?如果我想在不使用指针的情况下在重写函数中使用子类型,是否必须返回每个函数的基类,并将返回的类型转换为子类型?

解决方案

协变返回类型的概念是多态返回类型.在C ++中,没有指针或引用就无法拥有运行时多态性.让我们忽略第二大部分的困难,并假装这是可能的.这是我的代码,通过您的 Parent 界面处理事情:

  void bar(父母* p){自动o = p-> foo();} 

什么是 o ?好吧,当然是 Parent .在 Parent :: foo 的返回类型中这样说.但是,如果那个 p 指向一个 Child ,该怎么办?推导的 o 类型仍然是 Parent ,因此充其量我得到一个切片的对象.没有多态行为,因此整个练习毫无意义.

在最坏的情况下,而且很可能,我会得到不确定的行为.

这就是为什么协变返回类型必须是指针或引用的原因.

I create two simple classes by inheritance, and I add a virtual function and the override in the child class.

class Parent
{
public:
    virtual Parent foo();
};

class Child : public Parent
{
public:
    Child foo() override;
};

In this case, my overridden function get an error : error C2555: 'Child::foo': overriding virtual function return type differs and is not covariant from 'Parent::foo'

If I change return types with pointer :

class Parent
{
public:
    virtual Parent* foo();
};

class Child : public Parent
{
public:
    Child* foo() override;
};

the error gone ! I don't understand why the covariance of return types must be done with pointer and I can't use value type or a reference. Some website or forums explain that because the returned value is a copy of the value used in the function, the compiler know the constant size of a pointer, but must indicate different size for the overridden function and the parent function, which is apparently impossible.

So, why can't I use anything else than pointer in this case ? If I want the child type in the overridden function without using pointers, must I return the base class for each functions and cast the returned type into the child type ?

解决方案

The idea of a covariant return type is a polymorpihc return type. And in C++, you can't have run time polymorphism without pointers or references. Let's ignore for a second most of the hardships, and pretend it's possible. Here is my code that handles things by your Parent interface:

void bar(Parent * p) {
  auto o = p->foo();
}

What is o? Well, it's Parent of course. Says so in Parent::foo's return type. But what if that p is pointing at a Child? The deduced type of o is still Parent, so at best I get a sliced object. No polymorphic behavior, so the whole exercise is pointless.

At worst, and quite likely, I get undefined behavior.

That's why co-variant return types have to be pointers or references.

这篇关于C ++:没有指针的协变返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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