C++那些细节--中operator=相关问题

本文详细探讨了C++中operator=运算符的重载,从简介到深拷贝浅拷贝的概念,再到如何防止对象自我赋值和处理内存分配失败等问题。同时,文章强调了在派生类拷贝时考虑基类部分的重要性,并提供了去除冗余代码的策略。
摘要由CSDN通过智能技术生成

一.简介

operator= 运算符重载,就类似正常我们为变量赋值(如a = b)时的情况,但是我们自己写的类,内部肯定有各种字段,赋值当然不会就像a=b那么简单啦。


如果我们自己写重载操作符=,编译器也会为我们生成一个,但是这个函数功能很弱,只能实现浅赋值。


// C++Test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


class CopyTest
{
private:
	string name;
	int id;
public:
	CopyTest(int i, string n):id(i),name(n)
	{
		//cout<<"Construct!"<<endl;
	}

	~CopyTest()
	{
		//cout<<"No"<<id<<" "<<"Destruct!"<<endl;
	}

	void Display()
	{
		cout<<name<<" "<<id<<endl;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	CopyTest test1(1, "hehe");
	CopyTest test2(2, "haha");
	
	cout<<"Before operator = test2 is: ";
	test2.Display();

	test2 = test1;
	cout<<"After operator = test2 is ";
	test1.Display();

	system("pause");
	return 0;
}

结果:

Before operator = test2 is: haha 2
After operator = test2 is hehe 1
请按任意键继续. . .


可见,虽然我们并没有写那个operator=的函数,但是我们仍然实现了对象的赋值。


二.自己DIY一个operator=函数

// C++Test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


class CopyTest
{
private:
	string name;
	int id;
public:
	CopyTest(int i, string n):id(i),name(n)
	{
		//cout<<"Construct!"<<endl;
	}

	~CopyTest()
	{
		//cout<<"No"<<id<<" "<<"Destruct!"<<endl;
	}

	CopyTest& operator= (const CopyTest& e)
	{
		name = e.name;
		id = e.id;
		cout<<"operator= function is called!"<<endl;
		return *this;
	}

	void Display()
	{
		cout<<name<<" "<<id<<endl;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	CopyTest test1(1, "hehe");
	CopyTest test2(2, "haha");
	
	cout<<"Before operator = test2 is: ";
	test2.Display();

	test2 = test1;
	cout<<"After operator = test2 is ";
	test1.Display();

	system("pause");
	return 0;
}

结果:
Before operator = test2 is: haha 2
operator= function is called!
After operator = test2 is hehe 1
请按任意键继续. . .

这里我们就可以看到,系统调用了我们所写的operator=函数,完成了与系统为我们添加的函数相同的功能。


三.operator=返回一个本对象的引用

这里有个细节,要注意一下,同时这也是《Effictive C++》中的重要一条:

关于operator=函数的返回值,我们的返回值类型是对象本身的引用,return时使用的是this指针所指的位置的内容(即*this的值),为什么要这样呢?

对于=,我们可能会这样使用:
a = b = c;
//相当于:
a = (b = c);
即所谓的连锁赋值,赋值操作符必须返回一个reference指向操作符的左侧实参。

注意,这种操作在赋值操作中都成立。
CopyTest& operator= (const CopyTest& e)
       	{	...
		return *this;
	}
</pre><pre name="code"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值