协变克隆函数误解

时间:2015-03-21 04:20:13

标签: c++ c++11

这个问题与最近的问题有关 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(即指向基地的指针)。为什么是这样? bp->clone()应通过virtual Derived* Derived::clone指针调用协变Base*,因此bp->clone()的类型应为Derived*,而不是Base*

1 个答案:

答案 0 :(得分:2)

声明

auto funky = bp->clone();

相当于

Base* funky = bp->clone();

因为Base::clone会返回Base*

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

Base类型是多态的时,检查指针的类型是另一回事。并且在呈现的代码中Base是多态的,因为clone是虚拟的。要了解更多此功能,请检查指针的类型,而不仅仅是指针的类型。