繁体   English   中英

C++ 中的类型混淆

[英]Type Confusion in C++

我指的是这个链接

#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");

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

提到link ,它指出:

function 名称用作 vtable 的索引以查找要执行的正确(最具体)例程

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

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

有问题的代码会导致未定义的行为,因为b2不是Greeter* dynamic_cast将返回nullptr 。)一种可能的结果是sayHi的 vtable 条目将与Execute中的exec function 具有相同的索引,因此虽然源代码看起来会调用sayHi ,但它实际上会调用exec 或者它可能会崩溃。

但任何事情都可能发生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM