对象的协变返回类型 [英] Covariant Return Types of Objects

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

问题描述

以下代码。

#include <iostream>
using namespace std;
#include <stdio.h>


class mother {
    public:
     virtual mother* display() {};
};

class daughter : public mother
{
    public:
    daughter* display()
    {
        daughter *d1 = new daughter();
        std::cout << "This is the daughter" << std::endl;
        return d1;
    }

    void signature()
    {
        cout<<"I'm the sign"<<endl;
    }
};

int main() {
    //code
    mother *w = new daughter();
    daughter *w2 = w->display();
    w2->signature();
    return 0;
}

返回错误,表明无法从返回中分配子w2 w-> display()的值。但是据我所知,显示是一种虚拟功能。因此 w-> display()应该调用显示函数的子代变体,该子代变体具有子代的返回类型。那么到底为什么这不起作用,什么可以更改?

Returns an error that daughter w2 cannot be assigned from the return value of w->display(). But from what I know, display is a virtual function. So w->display() should call the daughter variation of the display function, which has a return type of daughter. Then exactly why isn't this working and what could be changed?

推荐答案

这是正确的行为,代码有错误:
mother :: display 返回指向 mother 的指针,您正在开车 <$ c $从句法上c> display 从指向母亲的指针。然后,您要求将指向母亲的指针转换为女儿的指针,这是垂头丧气,并非全部母亲在您的层次结构中是女儿,因此,您必须使用显式强制转换。这是语法。

This is the correct behavior, the code has a mistake: mother::display returns a pointer to mother, you are "driving" display from a pointer to mother, syntactically. Then you are asking to convert a pointer to mother to daughter, which is a "downcast", not all mothers are daughters in your hierarchy, so, you have to use an explicit cast. This is the syntax.

您知道 real 对象的类型为 daughter ,因此,它将返回类型为 mother 的类型,该类型为 daughter ,但这在语法中没有说明。编译器不会去实际执行您的源代码来编译它,这不是它的工作原理。

You "know" the real object is of type daughter, so, it will return a type of mother that is a daughter, but this is not said in the syntax. The compiler will not go and practically execute your source code to compile it, that is not how it works.

您可以这样做:

daughter *w2 = static_cast<daughter *>(w->display());

daughter *w2 = dynamic_cast<daughter *>(w->display());

仅在可以证明以下情况时使用 static_cast object确实是您说的类型,否则 dynamic_cast (并测试)。 static_cast 没有惩罚,编译器信任您。

Use static_cast only if you can prove the object is indeed of the type you say it is, dynamic_cast (and test) otherwise. static_cast has no penalty, the compiler "trusts" you.

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

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