(原創) constructor不能呼叫其他constructor (C/C++)
由於data member都需要初始化,所以會想將初始化data member的程式寫在某一個constructor中,這樣其他constructor就可以呼叫這個constructor達到code reuse,但我發現C++竟然不能這樣寫。
1#include <iostream>
2#include <string>
3
4using namespace std;
5
6class Foo {
7public:
8 int no;
9 string name;
10
11public:
12 Foo() {
13 Foo(50);
14 }
15
16 Foo(int no) {
17 this->no = no;
18 this->name = "John";
19 }
20};
21
22int main() {
23 Foo foo1;
24 cout << foo1.no << endl;
25 cout << foo1.name << endl;
26
27 Foo foo2(10);
28 cout << foo2.no << endl;
29 cout << foo2.name << endl;
30}
2#include <string>
3
4using namespace std;
5
6class Foo {
7public:
8 int no;
9 string name;
10
11public:
12 Foo() {
13 Foo(50);
14 }
15
16 Foo(int no) {
17 this->no = no;
18 this->name = "John";
19 }
20};
21
22int main() {
23 Foo foo1;
24 cout << foo1.no << endl;
25 cout << foo1.name << endl;
26
27 Foo foo2(10);
28 cout << foo2.no << endl;
29 cout << foo2.name << endl;
30}
執行結果
-858993460
10
John
10
John
執行結果會發現,foo1.no根本沒有被初始化,若用debug模式,會看到真的有執行到16行~18行內,當時的foo1.no值也的確被改了,但執行完結果卻仍然沒改,詳細原因不知,請教過陳俊杉教授,他說constructor是很特別的function,所以可能有特別的機制,所以若要重複使用某些code,還是只能用最原始方式,提出用private member function。
1/*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : ConstructorReuse.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Constructor can't invoke other constructor
7Release : 03/24/2007 1.0
8*/
9#include <iostream>
10#include <string>
11
12using namespace std;
13
14class Foo {
15public:
16 int no;
17 string name;
18
19public:
20 Foo() {
21 this->no = 50;
22 this->init();
23 }
24
25 Foo(int no) {
26 this->no = no;
27 this->init();
28 }
29
30private :
31 void init() {
32 this->name = "John";
33 }
34};
35
36int main() {
37 Foo foo1;
38 cout << foo1.no << endl;
39 cout << foo1.name << endl;
40
41 Foo foo2(10);
42 cout << foo2.no << endl;
43 cout << foo2.name << endl;
44}
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : ConstructorReuse.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Constructor can't invoke other constructor
7Release : 03/24/2007 1.0
8*/
9#include <iostream>
10#include <string>
11
12using namespace std;
13
14class Foo {
15public:
16 int no;
17 string name;
18
19public:
20 Foo() {
21 this->no = 50;
22 this->init();
23 }
24
25 Foo(int no) {
26 this->no = no;
27 this->init();
28 }
29
30private :
31 void init() {
32 this->name = "John";
33 }
34};
35
36int main() {
37 Foo foo1;
38 cout << foo1.no << endl;
39 cout << foo1.name << endl;
40
41 Foo foo2(10);
42 cout << foo2.no << endl;
43 cout << foo2.name << endl;
44}
執行結果
50
John
10
John
John
10
John
31行
void init() {
this->name = "John";
}
this->name = "John";
}
多了一個private init() member funtion,專門負責做data member初始化的動作,其他constructor只要invoke init()即可。
Conclusion
這是個很trivial的程式,只是我沒想到constructor竟然不能呼叫其他constructor,所以只能用這種最原始的方式達成,若有更好的方式,請告訴我,謝謝。