(原創) 如何在constructor中使用default argument? (C/C++)

在constructor中使用default argument,會使的程式更簡潔。

以下範例demo如何在constructor中使用default argument。

 1/* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : DefaultArgumentConstructor.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo how to use default argument with constructor
 7Release     : 01/13/2007 1.0
 8*/

 9#include <iostream>
10
11using namespace std;
12
13class Foo1 {
14public:
15  Foo1() : x(0{};
16  Foo1(int val) : x(val) {};
17
18public:
19  int x;
20}
;
21
22class Foo2 {
23public:
24  Foo2(int val = 0) : x(val) {}
25
26public:
27  int x;
28}
;
29
30int main() {
31  Foo1 foo11;
32  cout << foo11.x << endl;
33  Foo1 foo12(1);
34  cout << foo12.x << endl;
35
36  Foo2 foo21;
37  cout << foo21.x << endl;
38  Foo2 foo22(1);
39  cout << foo22.x << endl;
40}

class Foo1中,15行和16行使用了兩個constructor,但class Foo2中,26中只使用了一個constructor就完成了,關鍵就在使用了default argument,這種寫法使程式更加精簡。

posted on 2007-01-14 00:06  真 OO无双  阅读(761)  评论(0编辑  收藏  举报

导航