协变返回类型无效转换错误

时间:2015-05-09 20:20:52

标签: c++

我正在尝试协变返回类型并具有以下代码

class Base
{
public:
    virtual Base* clone() const
    {
        cout << "this is from Base " << endl;
        return new Base(*this);
    }
};

class Derived : public Base
{
public:
    virtual Derived* clone() const
    {
        cout << "this is from Derived " << endl;
        return new Derived(*this);
    }
};

int main()
{
    Base* d = new Derived;
    Derived* d2 = d->clone(); // invalid conversion from ‘Base*’ to   ‘Derived*’
    return 0;
}

为什么行Derived* d2 = d->clone();提供了无效的转化错误,因为Derived *类中clone返回的类型为Derived?如果我将其更改为Base* d2 = d->clone();它会运行,但它也会打印出来 &#34;这来自Derived&#34;表明它是被叫clone的{​​{1}}。

1 个答案:

答案 0 :(得分:4)

问题在于:

Derived* d2 = d->clone();

编译器检查编译类型的类型,d类型为Base*(即使在运行时虚拟调度启动,实际上Derived*对象从{{1}返回}})。在您的情况下,可以使用d->clone()(真的不需要static_cast),例如

dynamic_cast

我认为我们所有人都至少对此问题感到困惑。相关:Covariant clone function misunderstanding