Re: [問題] 想請教一個C++考題
※ 引述《james732 (好人超)》之銘言:
: 說到 constructor 不要呼叫 virtual function 的問題
: 最近才遇到一個 Java 與 C++ 行為很不一樣的範例
: (難怪 Effective C++ 的作者有特別提到與 Java 的差異...可惜剛看書時候還不懂)
: http://nopaste.csie.org/08053
: 這是化簡後的 Java code
: 簡單的說,parent class 留下了 foo() 這個函式供 child 去 override
: 當 clild 的建構子呼叫 parent 的建構子,就會執行 child 提供的 foo()
: 在 Java 裡,這程式會輸出 OK
: http://nopaste.csie.org/bd5f7
: 改寫成 C++,直覺是寫成這個樣子
: 可是 C++ 在這裡永遠執行 parent 的 foo,因此只會印出 ERROR
: 遇到這問題的時候,還真的挺驚訝的
: 再翻開 Effective C++,才知道為什麼作者會寫
: 「在 Constructor 裡面,virtual function 不是 virtual function」了
: (手邊沒書,不過應該是這個意思)
剛剛查了一下規格書
裡面有這段
Member functions, including virtual functions (10.3), can be called during
construction or destruction (12.6.2).When a virtual function is called
directly or indirectly from a constructor (including the mem-initializer or
brace-or-equal-initializer for a non-static data member) or from a destructor,
and the object to which the call applies is the object under construction or
destruction, the function called is the one defined in the constructor or
destructor’s own class or in one of its bases, but not a function overriding
it in a class derived from the constructor or destructor’s class, or
overriding it in one of the other base classes of the most derived object
(1.8). If the virtual function call uses an explicit class member access
(5.2.5) and the object-expression refers to the object under construction or
destruction but its type is neither the constructor or destructor’s own
class or one of its bases, the result of the call is undefined.
還給了一個範例
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
a->f(); // undefined behavior, a’s type not a base of B
}
--
C++ hello world標準寫法
http://nopaste.csie.org/fee97
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.134.226.149
※ 編輯: loveflames 來自: 140.134.226.149 (06/08 01:45)
推
06/08 01:53, , 1F
06/08 01:53, 1F
→
06/08 02:16, , 2F
06/08 02:16, 2F
→
06/08 02:17, , 3F
06/08 02:17, 3F
推
06/08 02:23, , 4F
06/08 02:23, 4F
→
06/08 02:23, , 5F
06/08 02:23, 5F
推
06/08 16:23, , 6F
06/08 16:23, 6F
討論串 (同標題文章)