相关疑难解决方法(0)

编译器如何为虚函数调用生成代码?

在此输入图像描述

CAT *p;
...
p->speak();
...
Run Code Online (Sandbox Code Playgroud)

有些书说编译器会将p-> speak()翻译为:

(*p->vptr[i])(p); //i is the idx of speak in the vtbl
Run Code Online (Sandbox Code Playgroud)

我的问题是:因为在编译时,不可能知道p的实际类型,这意味着不可能知道要使用哪个vptr或vtbl.那么,编译器如何生成正确的代码呢?

[改性]

例如:

void foo(CAT* c)
{
    c->speak();
    //if c point to SmallCat
    // should translate to (*c->vptr[i])(p); //use vtbl at 0x1234   
    //if c point to CAT
    // should translate to (*c->vptr[i])(p); //use vtbl at 0x5678  

    //since ps,pc all are CAT*, why does compiler can generate different code for them 
    //in compiler time?
}

...
CAT *ps,*pc;
ps = new SmallCat;  //suppose SmallCat's …
Run Code Online (Sandbox Code Playgroud)

c++

19
推荐指数
3
解决办法
1747
查看次数

什么时候在C++中创建VTable?

我想知道vtable何时创建?它是在main()之前的启动代码还是在其他时间点?

c++

10
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×2