动态强制转换无法识别成员

时间:2012-11-28 22:42:06

标签: c++ object dynamic-cast

我正在开展一个项目,我有两个班级:Room和EventRoom EventRoom继承自Room并拥有更多成员。

在我的代码中我这样做(tmpPtr是一个房间指针):

if(eventRoom)
     tmpPtr = dynamic_cast<EventRoom*>(tmpPtr);

以后我试试这个:

if(line == "false;")
     tmpPtr->setComplete(false);

我收到编译错误。 setComplete 是EventRoom

的成员

简短版本:我想创建Room类型的对象,在某些情况下还要创建EventRoom。该代码目前仅适用于Room,但是对于EventRoom,90%的代码都是相同的。有没有使用相同代码的方法? (使用dynamic_cast或类似的东西)

2 个答案:

答案 0 :(得分:3)

您需要tmpPtr作为EventRoot指针。

EventRoom* tmpPtr;

if(eventRoom)
     tmpPtr = dynamic_cast<EventRoom*>(tmpPtr);

您只能在Room指针上调用Room个公共方法。你不能只调用EventRoom - 方法。

答案 1 :(得分:1)

必须与RoomEventRoom一起使用的代码(也就是说,它只适用于Room接口),必须通过静态类型化的指针{{1 }}

使用Room*细节的代码必须通过静态类型EventRoom的指针。所以示例代码可能如下所示:

EventRoom*

您可以通过void someFunction(Room *myRoom) { // doRoomStuff must be a function declared in Room. myRoom->doRoomStuff(); // Try to determin if the room is an event room or not. This will // occur at runtime. EventRoom *myEventRoom = dynamic_cast<EventRoom*>(myRoom); if (myEventRoom) { // doEventRoomStuff is a function declared in EventRoom. You cannot call // myRoom->doEventRoomStuff even if 'myRoom' points to an object that is // actually an EventRoom. You must do that through a pointer of type // EventRoom. myEventRoom->doEventRoomStuff(); // doRoomStuff2 is a function that is declared in Room. Since every // EventRoom is also a room, every EventRoom can do everything that // rooms can do. myEventRoom->doRoomStuff2(); } myRoom->doRoomStuff3(); } 变量访问Room成员,但反之亦然。

相关问题