操作符=重载陷阱(赋值构造其实并没有执行赋值操作)

写测试用例如下:

#include<iostream>

using namespace std;

class Test
{
	public:
		Test &operator=(const Test&)
		{
			cout<<"operator="<<endl;
		};
};

int main()
{
	Test t1;
	Test t2 = t1;
}

执行后,结果为:

 可见,在对”=“执行操作符重载的时候,在main中=调用的时候并没有在操作符执行重载里面执行的输出语句 

再完善后做个测试:

#include<iostream>

using namespace std;

class Test
{
	public:
		Test()
		{
			cout<<"Constructor"<<endl;
		}
		Test &operator=(const Test&)
		{
			cout<<"operator="<<endl;
		};
};

int main()
{
	Test t1;
	Test t2 = t1;
}

执行后,结果为:

可见,在Test t2 = t1;中并不是执行的”=“赋值,而是执行的构造函数

再具体:

#include<iostream>

using namespace std;

class Test
{
	public:
		Test()
		{
			cout<<"Constructor"<<endl;
		}
		
		Test(const Test&)
		{
			cout<<"Copy Constructor"<<endl;
		}
		
		Test &operator=(const Test&)
		{
			cout<<"operator="<<endl;
		};
};

int main()
{
	Test t1;
	Test t2 = t1;
}

输出为:

 发现其实调用的是拷贝构造函数,拷贝构造函数又会调用一次标准构造函数

那么一开始的程序应该修改如下:

#include<iostream>

using namespace std;

class Test
{
	public:

		Test &operator=(const Test&)
		{
			cout<<"operator="<<endl;
		};
};

int main()
{
	Test t1;
	Test t2;
	t2 = t1;
}

执行结果如下:

 所以发现Test t2 = t1并没有执行 赋值操作,而是执行的拷贝构造函数

猜你喜欢

转载自blog.csdn.net/qq_36653924/article/details/127793463
今日推荐