一.简介
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= 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"