
編譯器會自動對建構函數的參數進行隱性型態轉換 (implicit type conversion) ,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | class Demo { |
| 004 | public: |
| 005 | int a; |
| 006 | |
| 007 | Demo(int pa) { |
| 008 | a = pa; |
| 009 | } |
| 010 | |
| 011 | void do_something() { |
| 012 | std::cout << a |
| 013 | << std::endl; |
| 014 | } |
| 015 | }; |
| 016 | |
| 017 | int main() { |
| 018 | Demo d = 3; |
| 019 | d.do_something(); |
| 020 | |
| 021 | return 0; |
| 022 | } |
| 023 | |
| 024 | /* Kaiching Chang |
| 025 | u0903_1.cpp |
| 026 | 2014-02 */ |
這裡直接將整數 3 指派給 Demo 型態的變數 d
| 018 | Demo d = 3; |
編譯執行並不會出錯
| $ g++ u0903_1.cpp |
| $ ./a.out |
| 3 |
| $ |
為了避免這種自動隱性型態轉換,可將建構函數宣告為 explicit ,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | class Demo2 { |
| 004 | public: |
| 005 | int a; |
| 006 | |
| 007 | explicit Demo2(int pa) { |
| 008 | a = pa; |
| 009 | } |
| 010 | |
| 011 | void do_something() { |
| 012 | std::cout << a |
| 013 | << std::endl; |
| 014 | } |
| 015 | }; |
| 016 | |
| 017 | int main() { |
| 018 | Demo2 d = 3; |
| 019 | d.do_something(); |
| 020 | |
| 021 | return 0; |
| 022 | } |
| 023 | |
| 024 | /* Kaiching Chang |
| 025 | u0903_2.cpp |
| 026 | 2014-02 */ |
這就是在建構函數的識別字前加上關鍵字 explicit
| 007 | explicit Demo2(int pa) { |
編譯時會發生錯誤訊息,如下
| $ g++ u0903_2.cpp |
| u0903_2.cpp:18:9: error: no viable conversion from 'int' to 'Demo' |
| Demo d = 3; |
| ^ ~ |
| u0903_2.cpp:3:7: note: candidate constructor (the implicit copy constructor) not |
| viable: no known conversion from 'int' to 'const Demo &' for 1st argument |
| class Demo { |
| ^ |
| 1 error generated. |
| $ |
continue ...
沒有留言:
張貼留言