構(gòu)造函數(shù),是一種特殊的方法 。主要用來在創(chuàng)建對(duì)象時(shí)初始化對(duì)象, 即為對(duì)象成員變量賦初始值,總與new運(yùn)算符一起使用在創(chuàng)建對(duì)象的語句中 。特別的一個(gè)類可以有多個(gè)構(gòu)造函數(shù) ,可根據(jù)其參數(shù)個(gè)數(shù)的不同或參數(shù)類型的不同來區(qū)分它們 即構(gòu)造函數(shù)的重載。
析構(gòu)函數(shù)(destructor) 與構(gòu)造函數(shù)相反,當(dāng)對(duì)象脫離其作用域時(shí)(例如對(duì)象所在的函數(shù)已調(diào)用完畢),系統(tǒng)自動(dòng)執(zhí)行析構(gòu)函數(shù)。
#include <iostream.h>
class animal
{
public:
animal()
{
cout<<"hello"<<endl;
}
~animal()
{
cout<<"析構(gòu)函數(shù)"<<endl;
}
void animal1();
};
void animal::animal1 () //構(gòu)造函數(shù)
{
int box[3],i,sum=0; //sun記得賦初值
cout<<"請(qǐng)輸入三個(gè)數(shù)"<<endl;
for(i=0;i<3;i++)
{
cin>>box[i];
sum=box[i]+sum;
}
cout<<sum<<endl;
}
int main()
{
animal sh;
sh.animal1 ();
return 0;
}