1. 赋值运算符重载格式
1.1 参数类型:const T&,传递引用可以提高传参效率
1.2 返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值
1.3 检测是否自己给自己赋值
1.4 返回*this :要复合连续赋值的含义
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
Date& operator=(const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
private:
int _year;
int _month;
int _day;
};
2. 赋值运算符只能重载成类的成员函数不能重载成全局函数
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
int _year;
int _month;
int _day;
};
// 赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
Date& operator=(Date& left, const Date& right)
{
if (&left != &right)
{
left._year = right._year;
left._month = right._month;
left._day = right._day;
}
return left;
}
// 编译失败:
// error C2801: “operator =”必须是非静态成员
因为没有显示赋值运算符重载的话,编译器会生成默认赋值运算符重载,此时再定义一个全局赋值运算符重载会冲突。
3.用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。
注意:内置类型是直接赋值的,自定义类型需要调用对应的赋值运算符重载完成赋值。
class Time
{
public:
Time()
{
_hour = 1;
_minute = 1;
_second = 1;
}
Time& operator=(const Time& t)
{
if (this != &t)
{
_hour = t._hour;
_minute = t._minute;
_second = t._second;
}
return *this;
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
private:
// 基本类型(内置类型)
int _year = 1970;
int _month = 1;
int _day = 1;
// 自定义类型
Time _t;
};
int main()
{
Date d1;
Date d2;
d1 = d2;
return 0;
}
编译器默认生成的赋值运算符重载已经可以解决问题了,为什么还要自定义呢?像日期这样的类自然不用定义,但遇到以下情况会产生一些问题,如下代码:
#include <iostream>
using namespace std;
// 这里会发现下面的程序会崩溃掉?这里就需要深拷贝去解决。
typedef int DataType;
class Stack
{
public:
Stack(int capacity = 10)
{
_array = (DataType*)malloc(sizeof(DataType) * capacity);
if (_array == NULL)
{
perror("malloc fail");
exit(-1);
}
_size = 0;
_capacity = capacity;
}
void Push(const DataType& x)
{
if (_size == _capacity)
{
_array = (DataType*)realloc(_array,2*_capacity*sizeof(DataType));
if (_array == NULL)
{
perror("realloc fail");
exit(-1);
}
_capacity *= 2;
}
_array[_size++] = x;
}
~Stack()
{
if (_array)
{
free(_array);
_array = nullptr;
_size = 0;
_capacity = 0;
}
}
private:
DataType* _array;
int _size;
int _capacity;
};
int main()
{
Stack s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
Stack s2;
s2 = s1;
return 0;
}
注意:如果类中未涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理则必
须要实现。
自定义实现赋值运算符重载进行深拷贝以解决两个_array指向同一块空间的问题。
定义以下赋值运算符重载进行深拷贝:
Stack& operator=(const Stack& s)
{
_array = (DataType*)realloc(_array, s._capacity * sizeof(DataType));
for (int i = 0; i < s._size; i++)
{
_array[i] = s._array[i];
}
_size = s._size;
_capacity = s._capacity;
return *this;
}