2016-04-12 159 views
1

所以我必須爲一個項目製作基於文本的視頻遊戲。我做了一個名爲「瓦」的類,然後是一個名爲「牆」的子類。然後我製作瞭如下所示的一系列拼貼。中心瓷磚,B2是一面牆。當我比較typeid(B2)==typeid(wall)時,即使圖塊B2是類型牆,它也會返回false。這個班,「戰士」有x和y分量。爲什麼typeid總是返回false?

//Initiate map 
    const int rows = 3; 
    const int cols = 3; 
    tile A1, A2, A3, B1, B3, C1, C2, C3; 
    fighter wizard(1, 2, 6, ft::mage, 100); 
    C3 = tile(wizard, "There's all this magic stuff everywhere."); 
    wall B2= wall("A wall blocks your path."); 
    tile map[rows][cols] = {{A1, A2, A3}, 
          {B1, B2, B3}, 
          {C1, C2, C3}}; 
... 

fighter player1(0, 0, 0, ft::warrior); 

... 

string input = ""; 
while(input!="quit") 
{ 
    cin >> input; 
    if (input == "left") { 
     if (typeid(map[player1.y][player1.x - 1]) == typeid(wall)) 
      cout << map[player1.y][player1.x - 1].scene; 
+2

那麼,爲什麼你認爲'圖[player1.y] [player1.x - 1]'是一堵牆?我會說這是一個純瓷磚(即使B2是一堵牆,因爲對象拷貝=> **切片**) – deviantfan

+0

http://stackoverflow.com/questions/274626/what-is-object-slicing – deviantfan

+1

@deviantfan在正確的軌道上。您正在創建'tile'對象的二維數組,當您嘗試將'wall'複製到數組中時,您將遇到問題。我猜你打算擁有一個'Tile *'類型的數組,它可以指向'Tile *'或'Wall *'類型,因爲'Tile *'是基類。 –

回答

1
tile map[rows][cols] 

房屋瓦片對象。如果你要檢查這些物體,你會發現它們屬於tile。不是原始B2對象的類型,wall。所以

if (typeid(map[player1.y][player1.x - 1]) == typeid(wall)) 

將始終比較tile == wall

如果您有興趣保留動態類型,您需要使用(智能)指針或任何引用原始對象的方式。這些對象需要具有動態類型/具有虛擬功能。

又見What is dynamic type of object