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

标签 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类(class)?如果我将其更改为 Base* d2 = d->clone();它运行,但也打印 “这是来自 Derived”,表明它是 cloneDerived叫。

最佳答案

问题出在这里:

Derived* d2 = d->clone();

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

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

我认为我们所有人都至少被这个问题困惑过一次。相关:Covariant clone function misunderstanding .

关于c++ - 协变返回类型无效转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30144607/

相关文章:

c++ - 关于如何使用 C++ 引用的困惑

c++ - OPENSSL 问题 - LINUX .cpp 代码

c++ - 将两个 vector 对转换为相应元素的映射

c++ - 如何从 C++ 发送双击键盘焦点对象?

c++ - 如何拆分大 switch 语句

c++ - 光线追踪归一化屏幕空间

c++ - 所以文件: function called from another so file than intended

c++ - 如何识别哪个 QObject 在 Qt 中发出信号?

C++ 更改打印队列所有者

c++ - 重复特定的正则表达式模式