歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++復制構造函數

C++復制構造函數

日期:2017/3/1 9:25:38   编辑:Linux編程

在C++中,下面三種對象需要調用拷貝構造函數(有時也稱“復制構造函數”):

1) 一個對象作為函數參數,以值傳遞的方式傳入函數體;
2) 一個對象作為函數返回值,以值傳遞的方式從函數返回;
3) 一個對象用於給另外一個對象進行初始化(常稱為復制初始化);

1.對象以值傳遞的方式傳入函數參數:

class CExample
{
private:
int a;

public:
//構造函數
CExample(int b)
{
a = b;
cout<<"creat: "<<a<<endl;
}

//拷貝構造
CExample(const CExample& C)
{
a = C.a;
cout<<"copy"<<endl;
}
//析構函數
~CExample()
{
cout<< "delete: "<<a<<endl;
}

void Show ()
{
cout<<a<<endl;
}
};

//全局函數,傳入的是對象
void g_Fun(CExample C)
{
cout<<"test"<<endl;
}

int main()
{
CExample test(1);
//傳入對象
g_Fun(test);

return 0;
}

2 對象以值傳遞的方式從函數返回

class CExample
{
private:
int a;

public:
//構造函數
CExample(int b)
{
a = b;
}

//拷貝構造
CExample(const CExample& C)
{
a = C.a;
cout<<"copy"<<endl;
}

void Show ()
{
cout<<a<<endl;
}
};

//全局函數
CExample g_Fun()
{
CExample temp(0);
return temp;
}

int main()
{
g_Fun();
return 0;
}

3)對象需要通過另外一個對象進行初始化

CExample A(100);
CExample B = A;

// CExample B(A);

Copyright © Linux教程網 All Rights Reserved