我正在尝试协变返回类型并具有以下代码
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”,表明它是 clone
在 Derived
叫。
最佳答案
问题出在这里:
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/