为什么 typeid 总是返回 false?

Why is typeid always returning false?

所以我必须为一个项目制作一个基于文本的视频游戏。我制作了一个名为 "tile" 的 class,然后是一个名为 "wall." 的子 class,然后制作了如下所示的瓷砖阵列。中间的瓷砖 B2 是一面墙。当我比较 typeid(B2)==typeid(wall) 它 returns false 即使瓷砖 B2 是墙类型。 class、"fighter" 有一个 x 和一个 y 分量。

  //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;
tile map[rows][cols]

存储图块对象。如果您检查这些对象,您会发现它们属于 class tile。不是原始 B2 对象 wall 的类型。所以

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

将始终比较 tile == wall

如果您对保留动态类型感兴趣,您需要使用(智能)指针或任何引用原始对象的方式。这些对象需要有一个动态的 type/have 虚函数。

另见 What is dynamic type of object