C++ 中的类型混淆

Type Confusion in C++

我指的是这个link

#include <iostream>
using namespace std;


class Base {}; // Parent Class

class Execute: public Base {   // Child of Base Class
public:
    virtual void exec(const char *program) 
    {
        system(program);
    }
};

class Greeter: public Base {   // Child of Base Class
public:
    virtual void sayHi(const char *str) 
    {
        cout << str << endl;
    }

};


int main() {

    Base *b1 = new Greeter();
    Base *b2 = new Execute();
    Greeter *g;

    g = static_cast<Greeter*>(b1); // Safe Casting to the same type "Greeter"
    g->sayHi("Greeter says hi!"); // String passed to sayHi() function

    g = static_cast<Greeter*>(b2); // Unsafe Casting to sibling class "Execute"
    g->sayHi("/usr/bin/xcalc"); // String passed to exec() function 
                                    // which will turn into a command to execute calculator

    delete b1;
    delete b2;
    return 0;
}

我的问题是关于陈述的:

g = static_cast<Greeter*>(b2);
g->sayHi("/usr/bin/xcalc");

b2 是类型 Execute 的实例。 b2 实例将有一个指向 vtable 的 vpointer,其中包含 exec() 的条目。当下一条语句调用g->sayHi(..)时,如何使用vtable查找调用哪个函数?

参考link,它指出:

the function name is used as index to the vtable to find the correct (most specific) routine to be executed

如果使用函数名称,那么如何在类型 Execute 的 vtable 中找到名称 sayHi

名称在编译时映射到 vtable 中的索引,因此在 运行 时函数调用只是数组查找。

有问题的代码导致未定义的行为,因为 b2 不是 Greeter*。 (dynamic_cast 会 return nullptr。)一个可能的结果是 sayHi 的 vtable 条目将具有与 exec 函数相同的索引 Execute,所以虽然源代码看起来会调用 sayHi,但实际上会调用 exec。否则它可能会崩溃。

但任何事情都有可能发生。