C++構造函數相關……

 構造函數是一種特殊的成員函數,用於給對象分配空間和初始 化。

1.構造函數名必須與類名相同,沒有返回值,不需要顯式(也無法)調用,在建立對象時自動執行。

2.拷貝構造函數

  拷貝構造函數是一種特殊的構造函數,參數是本類的對象。作用是用一個已經存在的對象初始化新建的對象。

#include <iostream>
using namespace std;
class leonard{
private:
    int x;

public:
    leonard()
    {
    x=10;
    cout<<"構造函數被調用1!"<<endl;
    }
    leonard(int m){
        x=m;
        cout<<"構造函數被調用2!"<<endl;
    }
    leonard(const leonard &d){
    x=2*d.x;
    cout<<"拷貝構造函數調用!"<<endl;
    }
    void print()
    {
        cout<<x<<endl;
    }
};
leonard fun2(){//函數的返回值類型爲leonard類
    leonard L1(88);//此時會調用普通的構造函數
    return L1;//調用fun2()結束時會調用一次拷貝構造函數
}
int main()
{
    leonard R1;//調用普通構造函數
    R1.print();
    leonard R2=R1;//調用拷貝構造函數
    R2.print();
    leonard R3(R1);//調用拷貝構造函數
    R3.print();
    R3=fun2();//調用普通構造函數和拷貝構造函數
    R3.print();
    return 0;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章