C++复制构造函数

在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);

posted @ 2015-08-24 14:24  zbjchaishen  阅读(287)  评论(0编辑  收藏  举报