1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include <iostream> class Demo { public : int a; int b; // 沒有參數的建構函數 Demo() { std::cout << "constructor clled.." << std::endl; a = b = 33; } // 一個參數的建構函數 Demo( int pa) { std::cout << "constructor clled.." << std::endl; a = b = pa; } // 兩個參數的建構函數 Demo( int pa, int pb) { std::cout << "constructor called.." << std::endl; a = pa; b = pb; } int do_something() { return a + b; } }; int main( void ) { Demo d1; std::cout << d1.do_something() << std::endl; Demo d2(5); std::cout << d2.do_something() << std::endl; Demo d3(12, 7); std::cout << d3.do_something() << std::endl; return 0; } /* 《程式語言教學誌》的範例程式 檔名:classdemo06.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
這裡定義了三個參數版本的建構函數
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // 沒有參數的建構函數 Demo() { std::cout << "constructor clled.." << std::endl; a = b = 33; } // 一個參數的建構函數 Demo( int pa) { std::cout << "constructor clled.." << std::endl; a = b = pa; } // 兩個參數的建構函數 Demo( int pa, int pb) { std::cout << "constructor called.." << std::endl; a = pa; b = pb; } |
編譯執行結果如下

中英文術語對照 | |
---|---|
建構函數 | constructor |
函數 | function |
重載 | overload |
您可以繼續參考
類別
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言