[問題] C++ constructor (建構子) 一問

看板C_and_CPP作者 (楓)時間13年前 (2011/05/28 23:30), 編輯推噓4(407)
留言11則, 7人參與, 最新討論串1/1
#include <iostream> using namespace std; class TestClass { public: TestClass() { this->a = 1; this->b = 1; this->c = 1; cout << "Call constructor TestClass()" << endl; } TestClass( int aa ) { TestClass(); this->a = aa; } ~TestClass() {} int getA() { return this->a; } int getB() { return this->b; } int getC() { return this->c; } private: int a; int b; int c; }; int main( int argc, char* argv[] ) { TestClass testClass( 2 ); cout << "a = " << testClass.getA() << endl; cout << "b = " << testClass.getB() << endl; cout << "c = " << testClass.getC() << endl; return 0; } ----- 以上是個簡單的例子來說明我的問題 上面程式我預期的結果是 Call constructor TestClass() a = 2 b = 1 c = 1 但在windows和linux跑出來的結果分別是 codeblocks on windows: Call constructor TestClass() a = 2 b = 2293544 c = 4273318 和 gcc 4.1.2 on linux Call constructor TestClass() a = 2 b = 0 c = 0 很顯然b,c沒被賦予值 但覺得奇怪的地方是明明有呼叫到TestClass()... 請問我的觀念錯在哪呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.123.105.140

05/28 23:52, , 1F
在class裡面不能呼叫自己的建構子 除非是base class的
05/28 23:52, 1F

05/28 23:52, , 2F
constructor不可以call constructor
05/28 23:52, 2F

05/28 23:52, , 3F
你那樣做他只是另外再建了一個local變數
05/28 23:52, 3F

05/28 23:53, , 4F
lifetime過了以後自然就被消滅了 雖然他的確有被呼叫過
05/28 23:53, 4F

05/28 23:56, , 5F
樓上正解 它並不是對this作用
05/28 23:56, 5F

05/29 00:06, , 6F
Java?
05/29 00:06, 6F

05/29 00:08, , 7F
原po想要的功能叫作 delegating constructor
05/29 00:08, 7F

05/29 00:08, , 8F
這個功能要等 C++0x 才會被加進標準
05/29 00:08, 8F

05/29 00:39, , 9F
最新的標準要修了
05/29 00:39, 9F

05/29 09:15, , 10F
推delegating ctor...現在還不支援><
05/29 09:15, 10F

05/29 15:13, , 11F
謝謝你們 我了解了!!!
05/29 15:13, 11F
文章代碼(AID): #1DuHJ-sJ (C_and_CPP)