專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計(jì)實(shí)例 >> 瀏覽文章

C++構(gòu)造函數(shù)與析構(gòu)函數(shù)的使用方法

作者:黃波海   來源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時(shí)間:2014年03月06日   【字體:

  構(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;
}

關(guān)閉窗口

相關(guān)文章