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

转载于:https://www.cnblogs.com/K2154952/p/4754649.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值