【发布时间】:2012-08-15 21:14:08
【问题描述】:
我正在参加一个 C++ 测验。并遇到了以下代码 - 这是非法的,但我不明白为什么。谁能解释为什么这条线:
Box* b1 = s1->duplicate();
生成编译器错误,“无法从 Shape* 转换为 Box”?
我假设s1->duplicate() 正在调用Box::duplicate(),因为s1 实际上指向Box - 但从编译器错误来看,它看起来像是在调用Shape::duplicate()。
#include <iostream>
struct Shape
{
virtual Shape* duplicate()
{
return new Shape;
}
virtual ~Shape() {}
};
struct Box : public Shape
{
virtual Box* duplicate()
{
return new Box;
}
};
int main(int argc, char** argv)
{
Shape* s1 = new Box;
Box* b1 = s1->duplicate();
delete s1;
delete b1;
return 0;
}
【问题讨论】:
-
因为this.
标签: c++ inheritance types typechecking