协变返回类型无效的转换错误
Covariant return type invalid conversion error
我正在尝试协变返回类型,并具有以下代码
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();
会出现无效的转换错误,因为它是clone
在Derived
类中返回的类型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();
我认为我们所有人至少对这个问题感到困惑。相关:协变克隆函数误解。
相关文章:
- C++使用params创建线程函数会导致转换错误
- 为什么g++在未执行的代码处标记强制转换错误
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- 如何在构建对象堆栈时解决转换错误?
- 执行具有转换错误的过程
- 指向类成员函数的指针中存在类型转换错误
- 为什么我在这里收到C++没有已知的转换错误?
- 增加图形转换错误
- 尝试向 COM 对象添加另一个接口时出现静态强制转换错误 C2440
- 返回带有另一个类的数据成员的构造函数?遇到转换错误?
- 指针和双重转换错误,代码没有
- 自定义函数转换错误?
- 将 C 程序转换为具有大量字符* 和无符号字符转换错误的C++
- 如何在我使用过的Arduino库之一中固定构造函数中的转换错误
- 试图使用strCMP时的char转换错误
- 我在 TSP 的C++解决方案中遇到转换错误
- "double(*)(string, double, double)"尝试传递函数C++时"double"转换错误
- 此语法中的构造函数转换错误
- Opengl 精度转换错误编译错误 E0415
- 无效的转换错误和无效的类型