(原創) 初學者使用Default Constructor容易犯的錯 (C/C++)
1
/*
2
(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4
Filename : DefaultConstrutor_CommonMistake.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Common mistake of Default Constructor
7
Release : 01/14/2007 1.0
8
*/
9
#include <iostream>
10
11
using namespace std;
12
13
class Foo {
14
public:
15
Foo(int x = 0) : x(x) {};
16
17
public:
18
int getX() { return this->x; }
19
20
private:
21
int x;
22
};
23
24
int main() {
25
Foo foo(2);
26
// Foo foo(); // error!!
27
// Foo foo; // OK!!
28
// Foo foo = Foo(); // OK!!
29
30
cout << foo.getX() << endl;
31
}
/* 2
(C) OOMusou 2007 http://oomusou.cnblogs.com3

4
Filename : DefaultConstrutor_CommonMistake.cpp5
Compiler : Visual C++ 8.0 / ISO C++6
Description : Common mistake of Default Constructor7
Release : 01/14/2007 1.08
*/9
#include <iostream>10

11
using namespace std;12

13
class Foo {14
public:15
Foo(int x = 0) : x(x) {};16

17
public:18
int getX() { return this->x; }19

20
private:21
int x;22
};23

24
int main() {25
Foo foo(2);26
// Foo foo(); // error!!27
// Foo foo; // OK!!28
// Foo foo = Foo(); // OK!!29

30
cout << foo.getX() << endl;31
}
25行若想帶2為初始值給Constructor,Foo foo(2)是對的,若不想帶值呢?26行的寫法是常犯的錯,Compiler會認為foo為一function,回傳Foo型別object,這算是C++蠻tricky的地方,所以正確的寫法是27行,不加上(),或28行寫法也可以,先利用Default Constructor建立一個temporary object,再使用Copy Constructor將object copy給foo,不過這是使用Copy-initialization的方式,和27行使用Direct-initialization的方式不一樣。


Foo(
浙公网安备 33010602011771号