C++建構函式例項講解
阿新 • • 發佈:2018-12-29
建構函式一直看不懂,動手試了一次,總算懂了個一二。功夫不負有心人!
#include <iostream> using namespace std; //建構函式在物件生成的時候會被自動呼叫 //如果定義了建構函式,則編譯器不生成預設的無引數建構函式 //一個類可以包含多個建構函式,物件使用哪個建構函式,取決於物件生成語句提供的引數型別、個數等 //一個物件必須初始化以後才能使用,而建構函式就是起到了這個初始化作用 //使用預設建構函式的類Test1 class Test1 { private: double real,imag; public : voidSet(double r,double i) { real=r; imag=i; } getData(double *pr,double *pi)//用此方法才能取出private中的值 { *pr=real; *pi=imag; } }; //沒有定義建構函式,編譯器自動生成預設建構函式 //自定義建構函式的Test2 class Test2 { private: double real,imag; public: Test2(double r,double i=0) //定義建構函式,函式名和類名一樣 { real=r; imag=i; } getData(double *pr,double *pi) { *pr=real; *pi=imag; } }; //多個建構函式Test3 class Test3 { private: double real,imag; public: Test3(double r,double i) //定義建構函式1 { real=r; imag=i; } Test3(double r) //定義建構函式2 { real =r; imag=0; } Test3(Test3 t1,Test3 t2) //定義建構函式3 { real=t1.real+t2.real; imag=t1.imag+t2.imag; } getData(double *pr,double *pi)//定義一般的函式 { *pr=real; *pi=imag; } }; int main() { Test1 t1; //預設建構函式被呼叫 t1.voidSet(1,2); double a,b; t1.getData(&a,&b); cout<<"a="<<a<<" b="<<b<<"\n"; //Test t2; //報錯,因為缺少建構函式的引數 Test2 t2(3,4); //第二個引數可以不設定,那麼就會預設設定為0 double c,d; t2.getData(&c,&d); cout<<"c="<<c<<" d="<<d<<"\n"; Test3 t3(3); //使用第一個建構函式,帶一個引數 double t30,t31,t32,t33,t34,t35; t3.getData(&t30,&t31); cout<<"t30="<<t30<<" t31="<<t31<<"\n"; Test3 tt3(3,4); //使用第二個建構函式,帶兩個引數 tt3.getData(&t32,&t33); cout<<"t32="<<t32<<" t33="<<t33<<"\n"; Test3 ttt3(t3,tt3); //使用第三個建構函式,引數為兩個Test3類物件 ttt3.getData(&t34,&t35); cout<<"t34="<<t34<<" t35="<<t35<<"\n"; return 0; }