2013-08-27 87 views
6

在問題其他類的虛擬方法中爲約calling virtual methods in ctors and dtors下面的源代碼塊被從C++標準的引用:在調用構建函數

struct V { 
    virtual void f(); 
    virtual void g(); 
}; 
struct A : virtual V { 
    virtual void f(); 
}; 
struct B : virtual V { 
    virtual void g(); 
    B(V*, A*); 
}; 
struct D : A, B { 
    virtual void f(); 
    virtual void g(); 
    D() : B((A*)this, this) { } 
}; 
B::B(V* v, A* a) { 
    f(); // calls V::f, not A::f 
    g(); // calls B::g, not D::g 
    v->g(); // v is base of B, the call is well-defined, calls B::g 

    // *** This line *** 
    a->f(); // undefined behavior, a’s type not a base of B 
    // ***************** 
} 

我的問題是:爲什麼在B的構造函數調用a->f()是一個未定義的行爲?我們可以放心地假設,a在傳遞給B的ctor之前已經被分配了,爲什麼不能正確地工作呢?當你創建D類型的對象

V * v = new V(); 
A * a = new A(); 
B * b = new B(v, a); 

回答

2

a->f()電話是不確定的。

在你自己的例子中,a->f()沒問題,因爲你在創建B實例之前創建了一個單獨的A實例。