赞
踩
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类
型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号。
用于内置类型的操作符,其含义不能改变,例如:内置的整型+,不 能改变其含义
注:.* 、:: 、sizeof 、?: 、. 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
函数原型:返回值类型 +operator+操作符+(参数列表)
例:
// 全局的operator==
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
//private:
int _year;
int _month;
int _day;
};
// 这里会发现运算符重载成全局的就需要成员变量是共有的,那么问题来了,封装性如何保证?
// 这里其实可以用我们后面学习的友元解决,或者干脆重载成成员函数。
bool operator==(const Date& d1, const Date& d2) {
return d1._year == d2._year;
&& d1._month == d2._month
&& d1._day == d2._day; }
void Test ()
{
Date d1(2018, 9, 26);
Date d2(2018, 9, 27);
cout<<(d1 == d2)<<endl;
}
运算符重载例子:
class Date { public: //全缺省的构造函数 Date(int year = 1900, int month = 1, int day = 1) { _year = year; _month = month; _day = day; } void PrintDate() { cout << _year << "-" << _month << "-" << _day << endl; } Date& operator++() { //运算符重载 _day += 1; return *this; } private: int _year; int _month; int _day; }; int main() { int a = 10; a++; Date d1(2019, 8, 1); Date d2(2019, 8, 1); d2 = d1++; system("pause"); return 0; }
赋值运算符重载:
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;
}
}
private:
int _year ;
int _month ;
int _day ;
};
Date类运算符重载案例
//完善的Date类 class Date { public: Date(int year = 1900, int month = 1, int day = 1); //全缺省函数构造 Date(const Date& d); //拷贝构造 Date& operator=(const Date& d); //赋值运算符的重载 Date operator+(int days); int operator+(const Date& d); Date& operator++(); //前置++ 运算符重载 Date operator++(int); //后置++ Date& operator--(); Date operator--(int); bool operator>(const Date& d)const; };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。