class complex{ pravate: double real,imag; public: viod set(double r,double i); };//編譯器自動生成默認構造函數 complex c1;//默認構造函數被調用 complex *pc=new complex;//默認構造函數被調用
e.g.數組
class complex{ private: double real,imag; public: complex(double r,double i=0); }; complex::complex(double r,double i){ real=r;imag=i; } complex c1;//error 缺乏構造函數的參數 complex *pc=new complex;//error 缺乏參數 complex c1(2);//OK complex c1(2,4),c2(3,5);//OK complex *pc=new complex(3,4);//OK
class cs{ int x; public: cs(){ cout<<"1 called"<<endl; } cs(int n){ x=n; cout<<"2 called"<<endl; } }; int main() { cs array1[2]; cout<<"step1"<<endl; cs array2[2]={4,5}; cout<<"step2"<<endl; cs array3[2]={3}; cs *array4=new cs[2]; delete []array4; return 0; } /* output: 1 called 1 called step 1 2 called 2 called step 2 2 called 1 called step3 1 called 1 called */
e.g.函數