[英]C++ invalid conversion error using covariant return types with virtual functions
In the following code, I can assign the return of the D::clone()
to a pointer to B
, but not a pointer to D
. 在下面的代码中,我可以将
D::clone()
的返回值分配给指向B
的指针,而不分配给D
的指针。 Is is possible to return the actual polymorphic type from a call of the base pointer? 是否可以从基本指针的调用中返回实际的多态类型?
struct B
{
virtual B * clone() { return this; }
};
struct D : B
{
D * clone()
{
std::cout << std::is_same<decltype(this), D *>::value << std::endl;
return this;
}
};
int main()
{
B * b = new D();
B * bb = b->clone(); // prints "1"
std::cout << std::is_same<decltype(b->clone()), D *>::value << std::endl; // prints "0"
D * d = b->clone(); // error: invalid conversion from B * to D * (GCC 5.1)
}
No. A call of clone()
on the base B
class of a D
will return the D*
cast to a B*
. 否。在
D
的基类B
上调用clone()
会将D*
强制转换为B*
。
You can reverse this by doing a static_cast<D*>
if you are absolutely certain, or a dynamic_cast<D*>
if you are not certain. 如果绝对确定,可以执行
static_cast<D*>
如果不确定,可以执行dynamic_cast<D*>
。 If you are certain, than you should really make the variable b
be a D*
. 如果可以肯定的话,则应该使变量
b
为D*
。
In C++, you should encode what you know about the state of the program at compile time regardless of the run time situation as types. 在C ++中,无论运行时的情况如何,都应在编译时对所了解的程序状态进行编码。 By storing the
D*
into B* b
, you are telling the compiler not to "know" that the data being pointed to "is a D
". 通过将
D*
存储到B* b
,您在告诉编译器不要 “知道”所指向的数据是“ D
”。 Instead, you are saying "the code using B*b
should be valid for any pointer-to- B
. Clearly D* d = b->clone();
is not guaranteed to be valid for every pointer-to- B
. 相反,您说的是“使用
B*b
的代码对任何指向B
指针都应该有效。显然D* d = b->clone();
不能保证对每个指向B
指针都有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.