在下面的代码中,我可以将 的返回值分配给D::clone()
指向 的指针B
,但不能分配指向 的指针D
。是否可以从基指针的调用中返回实际的多态类型?
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)
}