
除了可以在建構函數中設定資料成員外,資料成員也可以由初值串列 (initializar list) 來設定,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | class Demo { |
| 004 | public: |
| 005 | int a; |
| 006 | int b; |
| 007 | |
| 008 | Demo(int pa, int pb): a(pa), b(pb) { |
| 009 | std::cout << "constructor.." |
| 010 | << std::endl; |
| 011 | } |
| 012 | |
| 013 | int do_something() { |
| 014 | return a + b; |
| 015 | } |
| 016 | }; |
| 017 | |
| 018 | int main() { |
| 019 | Demo d(55, 44); |
| 020 | std::cout << d.do_something() |
| 021 | << std::endl; |
| 022 | |
| 023 | return 0; |
| 024 | } |
| 025 | |
| 026 | /* Kaiching Chang |
| 027 | u0902.cpp |
| 028 | 2014-02 */ |
初值串列在建構函數的名稱之後,加上一個冒號,然後是資料成員與小括弧中的參數
| 008 | Demo(int pa, int pb): a(pa), b(pb) { |
這樣就會將 pa 的值設定給 a , pb 的值設定給 b 。
編譯執行結果如下
| $ g++ u0902.cpp |
| $ ./a.out |
| constructor.. |
| 99 |
| $ |
continue ...
沒有留言:
張貼留言