【发布时间】:2015-01-07 03:00:50
【问题描述】:
在我的程序中,我有一个基类 (ship) 和四个派生类 (pirate、mercantile、repairing、exploring) 和一个成员函数 repairing 我想知道如果ship * 指向的对象属于pirate 类型,以便能够处理这种情况。
所以在那个成员函数中我有以下if:
ship * shp;
shp = map[i][j]->getShip(); //random initialization of shp
if( (dynamic_cast<pirate *>(shp)) == NULL) // <- program doesn't enter here
{ . . . } // while it should
但在运行时我注意到有时程序没有进入if,即使shp指向非pirate对象(例如exploring)。
所以我尝试通过编写以下代码来查看if 内的boolean 值的结果:
pirate *prt;
bool test;
if(map[i][j]->getShip()!=0){
prt = dynamic_cast<pirate *>(shp); // <- program crashes here
test = ( prt == NULL );
cout<<test<<endl;
}
但在编译并尝试运行此程序后,程序在使用dynamic_cast 时崩溃。
所以,dynamic_cast 可能无法正常工作,这就是它没有在前面的代码中输入if 的原因。
请注意,我在程序的其余部分中使用了与 dynamic_cast 相同的方法来找出对象的类型并且它工作正常。
为什么会这样?
提前致谢。
【问题讨论】:
-
如果您在第一个 if 语句中,则表示转换失败并且 shp 可能正在寻找一些无效值。因此,第二次尝试 dynamic_cast shp(很可能处于无效状态)将导致崩溃。您需要发布更多代码以进一步澄清。
-
map[i][j]->getShip()您是否 100% 确定 i 和 j 有效并且您没有超出地图范围?我假设 map 是一个二维数组。 -
我不建议将变量命名为与标准类相同的名称 (
map)。 -
Note that I have used the same method with dynamic_cast in the rest of my programm to find out the type of an object and it worked properly我们不知道map是什么。我们不知道i或j的值。如果您发布map是什么,以及当您的程序崩溃时i和j的值究竟是什么,这不是更有帮助吗?
标签: c++ crash dynamic-cast