在類別中
建構元扮演很重要的角色
它會幫助新建立的物件設定初值
建構元可以視為一種特殊的函數
建構元的名稱和所屬類別的名稱相同
建構元可以有引數
但不能有回傳值
建構元格式:
類別名稱 (型態1 引數1 ,型態2 引數2 ,…….){
………………..
(沒有傳回值)
}
Ex:
#include <iostream> using namespace std; class time { public: //定義建構元 time (int a,int b,double c){ hour=a; minute=b; second=c; } void show(void); private: int hour; int minute; double second; }; void time::show(){ cout << hour << " : " << minute << " : " << second << endl; } int main(){ time t1(12,12,12); //呼叫建構元 t1.show(); }
也可以將建構元寫在類別宣告外面:
Ex:
#include <iostream> using namespace std; class time { public: time (int,int,double); //建構元原型宣告 void show(void); private: int hour; int minute; double second; }; //定義建構元 time::time (int a,int b,double c){ hour=a; minute=b; second=c; } void time::show(){ cout << hour << " : " << minute << " : " << second <<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>< endl; } int main(){ time t1(12,12,12); //呼叫建構元 t1.show(); }