(C++,MinGW的4.4.0,Windows操作系統)C++:虛函數如何解決「this」指針作用域問題?
所有這一切都在評論代碼,除了標籤< 1>和< 2>,是我的猜測。請糾正我,如果你認爲我錯了地方:
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
}
< 2>是一個錯誤,是顯而易見的。爲什麼< 1>不是錯誤?我認爲這種調用的發生是: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);
那麼爲什麼< 1>沒有錯誤,而< 2>呢?
(我知道虛函數表是實現具體的東西,但我仍然認爲這是值得一問的問題)
確定但是'這個'被切成只知道'A'爲<1>。在成員函數內部,我認爲這些調用會解析爲'this-> whatEver'。令我困惑的是,由於「this」隱含地傳遞,如圖所示與B對象不同,該機制如何工作? – ustulation 2012-04-24 06:58:16
@ustulation:不,這個''是'B'類型,方法'B :: disp()'是被調用的方法,當然它有權訪問它自己的成員'x'。這裏沒有切片。 – 2012-04-24 07:02:39
真正的規則是在C++中,動態分派僅用於虛擬members_。你的規則是由此而來的,並且這個語言不允許將變量定義爲虛擬。 – 2012-04-24 07:24:25