运算符重载
为了增强程序的可读性,C++支持运算符重载 。所谓重载就是赋予这个操作符新的含义和功能,使之实现之前没有的功能。
运算符重载的特征为:
- operator + 合法的运算符 构成函数名(举例:重载<运算符的函数名:operator< )。
- 重载运算符以后,不能改变运算符的 优先级/结合性/操作数个数
以下以“==”赋值运算符重载为例
{
public :
Date()
{}
// 拷贝构造函数
Date (const Date& d)
{
_year = d ._year;
_month = d ._month;
_day = d ._day;
}
// ==操作符的重载
bool operator == (const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
private:
int _year ;
int _month ;
int _day ;
};
void Test ()
{
Date date1 ;
Date date2 = date1; //调用拷贝构造
date2==date1; //调用==运算符重载,可以使日期相等
}
5个C++不能重载的运算符是哪些?.* / :: / sizeof / ?: / .
类的赋值操作符重载
1.赋值运算符的重载是对一个已存在的对象进行拷贝赋值 。
2.当程序没有显式地提供一个以本类或本类的引用为参数的赋值运算符重载函数时,编译器会自动生成这样一个赋值运算符重载函数
{
public :
Date()
{}
// 拷贝构造函数
Date (const Date& d)
{
_year = d ._year;
_month = d ._month;
_day = d ._day;
}
// 赋值操作符的重载
// 1.思考为什么operator=赋值函数需要一个 Date&的返回值, 使用void做返回值可以吗?
Date& operator = (const Date& d)
{
// 2.这里的if条件判断是在检查什么?
if (this != &d)
{
this->_year = d. _year;
this->_month = d. _month;
this->_day = d. _day;
}
return *this ;
}
private:
int _year ;
int _month ;
int _day ;
};
void Test ()
{
Date date1 ;
Date date2 = date1; // 调用拷贝构造函数
Date date3 ;
date3 = date1 ; // 调用赋值运算符的重载
}