[問題] C++ constructor (建構子) 一問
#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
05/28 23:52, 1F
推
05/28 23:52, , 2F
05/28 23:52, 2F
→
05/28 23:52, , 3F
05/28 23:52, 3F
→
05/28 23:53, , 4F
05/28 23:53, 4F
→
05/28 23:56, , 5F
05/28 23:56, 5F
→
05/29 00:06, , 6F
05/29 00:06, 6F
推
05/29 00:08, , 7F
05/29 00:08, 7F
→
05/29 00:08, , 8F
05/29 00:08, 8F
→
05/29 00:39, , 9F
05/29 00:39, 9F
推
05/29 09:15, , 10F
05/29 09:15, 10F
→
05/29 15:13, , 11F
05/29 15:13, 11F