【发布时间】:2014-02-04 20:48:28
【问题描述】:
CAT *p;
...
p->speak();
...
有些书说编译器会将 p->speak() 翻译成:
(*p->vptr[i])(p); //i is the idx of speak in the vtbl
我的问题是:因为在编译时,不可能知道 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 vtbl address is 0x1234;
pc = new CAT; //suppose CAT's vtbl address is 0x5678;
...
foo(ps);
foo(pc)
...
有什么想法吗?谢谢。
【问题讨论】:
-
最后它是编译器实现特定的......
-
@camino 现在您的新箭头使图表看起来正确!
标签: c++