s->duplicate()
返回一个类型为 Box*
的对象,但我在使用 Box*
初始化时出现了错误。看起来它被转换回了 Shape*
。如果它被转换回基类指针,那么有什么意义使用协变返回类型呢?
struct Shape
{
virtual Shape* duplicate()
{
return new Shape;
}
};
struct Box : Shape
{
virtual Box* duplicate()
{
return new Box;
}
};
int main()
{
Shape* s = new Box;
Box* b = s->duplicate();
}
错误:
main.cpp:22:12: error: cannot initialize a variable of type 'Box *' with an rvalue of type 'Shape *'
Box* b = s->duplicate();
^ ~~~~~~~~~~~~~~
1 error generated.
Shape* s = new Box();
。 - Lightness Races in Orbit