
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++ ×2