协变克隆功能误解 [英] Covariant clone function misunderstanding

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

问题描述

这个问题与最近的一个问题有关多态不适用于相同数据类型(基类和继承的类)的函数返回值

This question is related to a very recent one Polymorphism is not working with function return values of same data type (Base and Inherited class)

考虑代码:

#include <iostream>
#include <typeinfo>

class Base
{
public:
    virtual  Base * clone()
    {
        Base * bp = new Base ;
        return bp ;
    }
};

class Derived: public Base
{
public:
    Derived * clone() override
    {
        Derived * dp = new Derived ;
        return dp ;
    }
};

int main() 
{
    Base * bp = new Derived;
    auto funky = bp->clone();
    std::cout << typeid(funky).name() << std::endl;
}

输出为 P4Base (即指向Base的指针).为什么是这样? bp-> clone()应该通过 Base * 指针调用协变 virtual Derived * Derived :: clone ,因此 bp-> clone()应该是 Derived * ,而不是 Base * .

The output is P4Base (i.e. pointer-to-Base). Why is this? bp->clone() should invoke the covariant virtual Derived* Derived::clone via a Base* pointer, so the type of bp->clone() should be Derived*, not Base*.

推荐答案

声明

auto funky = bp->clone();

等同于

Base* funky = bp->clone();

因为 Base :: clone 返回 Base * .

检查该指针的类型,然后产生 Base * .

Checking the type of that pointer then yields Base*.

Base 类型是多态的时,检查pointe的类型是另一回事.在给出的代码中, Base 是多态的,因为 clone 是虚拟的.要了解更多有关此功能的信息,请检查指针对象的类型,而不仅仅是指针的类型.

Checking the type of the pointee is a different matter, when the Base type is polymorphic. And in the presented code Base is polymorphic because clone is virtual. To understand more of this functionality, check the type of the pointee instead of just the type of the pointer.

这篇关于协变克隆功能误解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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