拷贝构造函数与 "=" 操作符


#include <iostream>
using namespace std;

class CTest
{
public:
    CTest(int aa): a(aa) { cout << "constructor: a = " << a << endl; }
    CTest(const CTest &in)
    {
        a = in.a;
        cout << "copy constructor" << endl;
    }
    ~CTest() { cout << "desctructor: a = " << a << endl; }
    CTest& operator=(const CTest &in)
    {
        a = in.a;
        cout << "operator=" << endl;
        return *this;
    }
public:
    int a;
};

int main()
{
    CTest test1 = CTest(10);    // 调用普通构造函数初始化(直接初始化)
    CTest test2(CTest(11));     // 调用普通构造函数初始化(直接初始化)
    CTest test3(test1);         // 调用拷贝构造函数初始化
    CTest test4 = test1;        // 调用拷贝构造函数初始化
    test4 = test2;              // 赋值操作符
    cout << "end" << endl;
    return 0;
}
输出:

constructor: a = 10
constructor: a = 11
copy constructor
copy constructor
operator=
end
desctructor: a = 11
desctructor: a = 10
desctructor: a = 11
desctructor: a = 10

1. 编译器会默认添加拷贝构造函数和拷贝赋值操作符(=),当然,用户也可以自己写,即重载;

2. "=" 在不同时期含义不同:初始化时期 "=" 调用的是“拷贝构造函数”(如果右边是非临时对象,如 CTest test4 = test1, ),后期赋值是调用的“拷贝赋值操作符”(如 test4 = test2);

3. 区分什么时候是调用普通构造函数初始化(直接初始化),什么时候是调用拷贝构造函数初始化。如 CTest test1 = CTest(10)CTest test2(CTest(11)) 都是直接初始化。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值