
類別的 static 的成員不能在類別中建立初值,但是有一種例外,就是宣告為 const 的常數,舉例如下
| 001 | #include <iostream> |
| 002 | |
| 003 | class Demo { |
| 004 | public: |
| 005 | static int get_day() { |
| 006 | return days; |
| 007 | } |
| 008 | |
| 009 | private: |
| 010 | static const int days = 30; |
| 011 | }; |
| 012 | |
| 013 | int main() { |
| 014 | std::cout << Demo::get_day() |
| 015 | << std::endl; |
| 016 | |
| 017 | return 0; |
| 018 | } |
| 019 | |
| 020 | /* Kaiching Chang |
| 021 | u0910.cpp |
| 022 | 2014-02 */ |
static const 的資料成員可以直接設定初值
| 010 | static const int days = 30; |
編譯執行,結果如下
| $ g++ u0910.cpp |
| $ ./a.out |
| 30 |
| $ |
continue ...
沒有留言:
張貼留言
0.留言請選擇註冊帳號, Google 或 OpenID 均可
1.歡迎留言交流,但不歡迎垃圾留言及廣告留言
2.文章相關問題歡迎提出,請減少情緒性留言
3.非文章相關內容,請到 G+ 社群或 FB 社團提出
4.問作業之留言會被直接刪除
5.莫忘網路禮節
6.可使用部份HTML標記,如 <b> 、 <i> 、 <a>
7.站長保留刪除留言的權力