构造函数 拷贝构造函数 赋值构造函数笔记

class Test
{
private:
int m_nTest;
public:
Test(int x);
Test(const Test &);
Test& operator =(const Test&);
~Test();
void func(Test temp)
{
}
};
Test :: Test(int x) :m_nTest(x)
{
cout << "带参构造函数" << endl;
}
Test :: Test(const Test &other)
{
m_nTest = other.m_nTest;
cout << "拷贝构造函数" << endl;
}
Test& Test :: operator =(const Test& other)
{
cout << "赋值构造函数" << endl;
if (this == &other)
{
return *this;
}
else
{
m_nTest = other.m_nTest;
}
return *this;
}
Test :: ~Test()
{
}
int main()
{
Test a(2);//带参构造函数
Test b(3);//带参构造函数
a = b;//赋值构造函数
Test c = a;//拷贝构造函数
b.func(a);实际上a是作为参数传递给b.func(Test temp),即Test temp = a;和上一个一致,是拷贝构造函数,不是赋值构造函数。
return 0;
}
拷贝构造函数的参数之所以使用引用类型是为了避免拷贝构造函数无限制的递归下去
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值