![这里写图片描述](//img-blog.csdn.net/20180313230549892?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L1lvdW5nX19GYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
m_x = 0;
m_y = 0;
}
Test(int x,int y)
{
m_x = x;
m_y = y;
}
void printT()
{
cout << "x = " << m_x << " y = " << m_y << endl;
}
Test(const Test &another)
{
cout << "Test(const Test &)..." << endl;
m_x = another.m_x;
m_y = another.m_y;
}
#if 0
Test(const Test &another)
{
m_x = another.m_x;
m_y = another.m_y;
}
#endif
void operator=(const Test &another)
{
m_x = another.m_x;
m_y = another.m_y;
}
private:
int m_x;
int m_y;
};
int main()
{
Test t1(100,200);
Test t2(t1);
t2.printT();
Test t3 = t1;
Test t4;
t4 = t1;
return 0;
}
Test t2(t1);使用默认拷贝构造函数
t2.printT();
Test t3 = t1;与上面的写法等价,依然是使用了默认拷贝构造函数
//构造函数是对象初始化的时候调用
Test t4;
t4 = t1;调用的不是t3的拷贝构造函数,而是t3的赋值操作符函数
会有一个默认的拷贝构造函数
Test(const Test &another)//加const:只读another
{
m_x = another.m_x;
m_y = another.m_y;
}
等号=赋值操作符重载(默认的),这里将其显示出来
void operator=(const Test &another)
{
m_x = another.m_x;
m_y = another.m_y;
}
![这里写图片描述](//img-blog.csdn.net/20180314135028584?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L1lvdW5nX19GYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)