目录
3、用户没有显式实现时,编译器会自动生成一个默认的赋值操作符重载,以值的方式逐字节拷贝
1、运算符重载
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也是具有其返回值类型,函数名字以及参数列表,其返回值类型和参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号;
函数原型:返回值类型 operator操作符(参数列表)。
注意:
1.不能通过链接其他符号来创建新的操作符:比如 operator@;
2.重载操作符必须有一个类类型参数;
3.用于内置类型的运算符,其含义不能改变,例如:内置类型的+,不能改变其含义;
4.作为类成员函数重载时,其形参看起来比操作书数数目少1,因为成员函数的第一个参数为隐藏的this;
5. .* :: sizeof ?: . 注意以上五个运算符不能重载,这个经常在笔试选择题中出现。
//运算符重载
bool operator<(const Date& d);
bool operator==(const Date& d);
bool operator<=(const Date& d);
bool operator>(const Date& d);
bool operator>=(const Date& d);
bool operator!=(const Date& d);
//函数实现
bool Date::operator<(const Date& d)
{
if (_year < d._year)
return true;
else if (_year == d._year)
{
if (_month < d._month)
return true;
else if (_month == d._month)
return _day < d._day;
}
return false;
}
bool Date::operator==(const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
bool Date::operator<=(const Date& d)
{
return *this < d && *this == d;
}
bool Date::operator>(const Date& d)
{
return !(*this <= d);
}
bool Date::operator>=(const Date& d)
{
return !(*this <d);
}
bool Date::operator!=(const Date& d)
{
return !(*this == d);
}
当我们重载了 < 和 == 时,就可以复用这两个运算符,重载<= > >= != ,更加方便了。
2、赋值运算符重载
1、赋值运算符重载格式
1.参数类型:const 参数名&,传递引用可以提高传参效率,(不用再调用拷贝构造了);
2.返回值类型:参数名& 返回引用可以提高返回的效率,有返回值的目的是为了支持连续赋值;
3.检测是否自己给自己赋值
4.返回this,要符合连续赋值的含义;
//声明
Date& operator=(const Date& d);
//定义
Date& Date:: operator=(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
}
2、赋值运算符只能重载成成员函数,不能重载成全局函数
因为赋值运算符第一个参数是this指针,重载成全局函数,就需要传this指针,而当类里面没有显式定义赋值运算符时,编译器会自动生成一个默认的。此时就会和类外的赋值运算符重载形成冲突,所以赋值运算符只能是成员函数。
3、用户没有显式实现时,编译器会自动生成一个默认的赋值操作符重载,以值的方式逐字节拷贝
注意:内置类型成员变量是直接赋值的,而自定义成员变量需要调用对应类的赋值运算符重载完成赋值,如果自定义类中没有显式实现赋值运算符重载,编译器也会默认生成赋值重载;
class Time
{
public:
Time()
{
_hour = 1;
_minute = 1;
_second = 1;
}
//这个赋值运算符重载写不写都可以,不写的话编译器也会自动生成
/*Time& operator=(const Time& t)
{
if (this != &t)
{
_hou