Posted on March 4th, 2010 at 0:07 by fr3@K
這幾個月忙於工作, 這個部落格都快被我給荒廢掉了. 昨晚終於花了時間完成了一篇積了一兩個月, 說明 virtual function 在執行時期的 override 過程以及 virtual function 與 constructor/destructor 混搭結果 的文字.
今天我準備了個題目給花了時間看了它的朋友, 當作對小弟的說明能力來個測驗. 請問, 下面的 code snip 的輸出結果是什麼?
C++:
-
#include <typeinfo>
-
#include <iostream>
-
-
using namespace std;
-
-
struct Base
-
{
-
Base()
-
{
-
this->print_type_name();
-
}
-
virtual void print_type_name()
-
{
-
cout <<typeid(*this).name() <<endl;
-
}
-
};
-
struct Derived : Base
-
{
-
};
-
-
int main()
-
{
-
Derived d;
-
d.print_type_name();
-
return 0;
-
}
也就是說, 對同一個, 沒有被 override 過的 virtual function - Base::print_type_name - 呼叫兩次 (第一次是透過 Base 的 ctor 間接呼叫, 第二次則是當 Derived 的 object instance 直接呼叫) 的輸出是什麼? And why?
有些事情, 可以是做爽的. 而這些文字除了幫助降低自己 (主要是在工作上) 對相同主題重複一再說明的負擔, 它們還蘊藏著我的理想性 - 我衷心期望它們能夠對華文技術圈有所助益. 也希望我的說明能力不要太差, 讓這些文字淪落到寫爽的.
Hope you have fun while figuring out the quiz.
![]() |
|
| Previous Post « 當 Constructor 遇上 Virtual Function « |
Next Post » Pic of starryalley on iThome » |








不考慮 compiler 怎麼 encode type name 。印出:Base 再印出 Derived 。
因為當 Constructor 遇上 Virtual Function說:
建構一個 Derived 的 object instance 時, 先被建構的是其父類別,因此此時 typeid 會是拿到 Base class 。待子類別建構完成後、在 main() 中的 d.print_type_name(); 呼叫才會拿到 Derived 。
Comment by Keiko — March 4, 2010 @ 13:46