2012-11-28 29 views
0

我正在研究一个项目,其中有两个班级:会议室和活动室 会议室继承自会议室并拥有更多会员。动态演员无法识别成员

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

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

后来当我试试这个:

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

我得到的编译错误。 的setComplete是EventRoom

短版的一员:我想创造型房的对象,在某些情况下EventRoom。该代码目前仅适用于Room,但90%的代码对于EventRoom而言是相同的。任何使用相同代码的方式? (与dynamic_cast或类似的东西)

回答

3

你需要tmpPtr是一个EventRoot指针。

EventRoom* tmpPtr; 

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

只能调用一个Room指针Room公共方法。您无法拨打EventRoom - 仅限于方法。

+0

但是它也能用于房间吗?或者我需要2个不同的指针,每个坐标1个? –

+0

@Yoan是的,它可以用于'房间',因为'EventRoom' **是一个**房间。 – juanchopanza

+0

@juanchopanza取决于“与'房间”一起工作的含义。“无法将'Room *'分配到'EventRoom *'中(没有投射)。 – Angew

1

其具有与两个RoomEventRoom工作(即,它仅与Room接口作品)中的代码,具有通过一个指向工作静态类型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(); 
} 

您可以通过EventRoom*变量访问Room成员,而不是相反。

+0

这是一篇很好的文章。我正在写一些非常相似的东西,但看到你的帖子后,我选择编辑它来为你的代码添加一些评论,以更强调一些事情。 –

+0

@NikBougalis感谢编辑,很好。 – Angew