【发布时间】:2012-04-24 06:44:48
【问题描述】:
(C++,MinGW 4.4.0,Windows 操作系统)
代码中的所有注释,除了标签 和 ,都是我的猜测。如果您认为我在某处错了,请纠正我:
class A {
public:
virtual void disp(); //not necessary to define as placeholder in vtable entry will be
//overwritten when derived class's vtable entry is prepared after
//invoking Base ctor (unless we do new A instead of new B in main() below)
};
class B :public A {
public:
B() : x(100) {}
void disp() {std::printf("%d",x);}
int x;
};
int main() {
A* aptr=new B; //memory model and vtable of B (say vtbl_B) is assigned to aptr
aptr->disp(); //<1> no error
std::printf("%d",aptr->x); //<2> error -> A knows nothing about x
}
是一个错误并且很明显。为什么 不是错误?我认为此调用发生的情况是:参数中的aptr->disp(); --> (*aptr->*(vtbl_B + offset to disp))(aptr) aptr 是指向成员函数的隐式this 指针。在disp() 内部,我们将有std::printf("%d",x); --> std::printf("%d",aptr->x); SAME AS std::printf("%d",this->x); 那么为什么 没有给出错误而 给出了?
(我知道 vtables 是特定于实现的东西,但我仍然认为值得提出这个问题)
【问题讨论】:
标签: c++ virtual-functions mingw32