由於data member都需要初始化,所以會想將初始化data member的程式寫在某一個constructor中,這樣其他constructor就可以呼叫這個constructor達到code reuse,但我發現C++竟然不能這樣寫。

 1(原創) constructor不能呼叫其他constructor (C/C++)#include <iostream>
 2(原創) constructor不能呼叫其他constructor (C/C++)#include <string>
 3(原創) constructor不能呼叫其他constructor (C/C++)
 4(原創) constructor不能呼叫其他constructor (C/C++)using namespace std;
 5(原創) constructor不能呼叫其他constructor (C/C++)
 6}


執行結果

(原創) constructor不能呼叫其他constructor (C/C++)-858993460
(原創) constructor不能呼叫其他constructor (C/C++)
(原創) constructor不能呼叫其他constructor (C/C++)
10
(原創) constructor不能呼叫其他constructor (C/C++)John


執行結果會發現,foo1.no根本沒有被初始化,若用debug模式,會看到真的有執行到16行~18行內,當時的foo1.no值也的確被改了,但執行完結果卻仍然沒改,詳細原因不知,請教過陳俊杉教授,他說constructor是很特別的function,所以可能有特別的機制,所以若要重複使用某些code,還是只能用最原始方式,提出用private member function。

 1}


執行結果

(原創) constructor不能呼叫其他constructor (C/C++)50
(原創) constructor不能呼叫其他constructor (C/C++)John
(原創) constructor不能呼叫其他constructor (C/C++)
10
(原創) constructor不能呼叫其他constructor (C/C++)John


31行

}


多了一個private init() member funtion,專門負責做data member初始化的動作,其他constructor只要invoke init()即可。

Conclusion
這是個很trivial的程式,只是我沒想到constructor竟然不能呼叫其他constructor,所以只能用這種最原始的方式達成,若有更好的方式,請告訴我,謝謝。

相关文章: