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

Covariant return type invalid conversion error

本文关键字:转换 错误 无效 返回类型      更新时间:2023-10-16

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

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();会出现无效的转换错误,因为它是cloneDerived类中返回的类型Derived *?如果我将其更改为 Base* d2 = d->clone();,它将运行,但也会打印"这是来自派生的",指示它是Derived中的clone

问题在这里:

Derived* d2 = d->clone();

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

Derived* d2 = static_cast<Derived*>(d)->clone();

我认为我们所有人至少对这个问题感到困惑。相关:协变克隆函数误解。