• 專注電子技術學習與研究
    當前位置:單片機教程網 >> MCU設計實例 >> 瀏覽文章

    C++構造函數與析構函數的使用方法

    作者:黃波海   來源:本站原創   點擊數:  更新時間:2014年03月06日   【字體:

      構造函數,是一種特殊的方法 。主要用來在創建對象時初始化對象, 即為對象成員變量賦初始值,總與new運算符一起使用在創建對象的語句中 。特別的一個類可以有多個構造函數 ,可根據其參數個數的不同或參數類型的不同來區分它們 即構造函數的重載。

    析構函數(destructor) 與構造函數相反,當對象脫離其作用域時(例如對象所在的函數已調用完畢),系統自動執行析構函數。

    #include <iostream.h>
    class animal
    {
    public:
    animal()
    {
    cout<<"hello"<<endl;
    }
    ~animal()
    {
    cout<<"析構函數"<<endl;
    }
    void animal1();

    };
    void animal::animal1 ()  //構造函數
    {
    int box[3],i,sum=0; //sun記得賦初值
    cout<<"請輸入三個數"<<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;
    }

    關閉窗口

    相關文章

    亚洲一区二区制服在线|在绩专区欧美自拍日韩|青春娱乐网97超碰人人射|在线观看国产网址你懂的