- 1.赋值运算符重载
- 1.1运算符重载
- 2.const成员
- 3.取地址及const取地址操作符重载
C ++ 中预定义的运算符的操作对象只能是内置类型。但实际上,对于许多用户自定义类,也需要类似的运算操作,所以就出现了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号。
函数原型:返回值类型 operator操作符(参数列表)
下面一日期类举个例子
class Date
{
public:
Date(int year = 2021, int month = 11, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
bool operator==(const Date& d1, const Date& d2)
{
return d1._year == d2._year;
&& d1._month == d2._month
&& d1._day == d2._day;
}
private:
int _year;
int _month;
int _day;
};
void TestDate()
{
Date d(2021, 10, 29);
Date d1(2022, 11, 11);
cout << (d == d1) << endl;
}
因为有隐含的this指针在,所以要注意。
在来个比较2个日期的大小。
bool Date::operator >(const Date& x)
{
if (_year > x._year)
{
return true;
}
else if (_year == x._year && _month > x._month)
{
return true;
}
else if (_year == x._year && _month == x._month && _day > x._day)
{
return true;
}
else
{
return false;
}
}
自己还可以试试重载 <,<=等等自己需要的。
重载需要注意的点:
1用于内置类型的操作符,其含义不能改变,例如:内置的整型+,不 能改变其含义
2作为类成员的重载函数时,其形参看起来比操作数数目少1成员函数的
3操作符有一个默认的形参this,限定为第一个形参
4.* 、:: 、sizeof 、?: 、. 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
###1.2 赋值运算符重载
赋值运算符有4点:
- 参数类型
- 返回值
- 检测是否自己给自己赋值
- 返回*this
- 一个类如果没有显式定义赋值运算符重载,编译器也会生成一个,完成对象按字节序的值拷贝。
Date& Date::operator=(const Date& x)
{
if (*this != x)
{
_year = x._year;
_month = x._month;
_day = x._day;
}
return *this;
}
class Date
{
public:
Date(int year = 2021, int month = 11, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Display()
{
cout << "Display ()" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
void Test()
{
Date d1(2021,11,11);
d1.Display();
const Date d2;
d2.Display();
}
如何让d2调得动Display呢?
加上const对d1是没有影响的
这就是const成员和const成员函数。
这两个默认成员函数一般不用重新定义 ,编译器默认会生成。
class Date
{
public:
Date* operator&()
{
return this;
}
const Date* operator&()const
{
return this;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比
如想让别人获取到指定的内容!



