運算符重載:
重載,就是重新賦予新的含義。運算符重載的方法是定義一個重載運算符的函數,使指定的運算符不僅能實現原有的,而且能實現在函數中指定的新的功能。在使用被重載的運算符時,系統會自動調用該函數,以實現相應的功能。即運算符重載實質是函數的重載。
重載運算符的格式如下:
函數類型 operator 運算符名稱(形參表)
{
對運算符的重載處理
}
c++中絕大多數的運算符容許重載,不能重載的運算符只有5個:即
. (成員訪問運算符)
* (成員指針訪問運算符)
:: (域運算符)
sizeof (長度運算符)
?: (條件運算符)
例:創建一個Date類,實現日期+天數=日期,日期-天數=日期及日期-日期=天數。
#define _CRT_SECURE_NO_WARNING 1 #include<iostream> using namespace std; class Date { public: friend ostream& operator<<(ostream&os, Date&d); Date(int year = 1900, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) { if (IsRightDay()) { _year = 1900; _month = 1; _day = 1; } } 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; } Date operator+(int day) { Date d(*this); d._day += day; while(d._day > DayInMonth()) { d._day -= DayInMonth(); if (d._month == 12) { d._month = 1; d._year += 1; } else d._month += 1; } return d; } Date &operator+=(int day) { _day += day; while (_day > DayInMonth()) { _day -= DayInMonth(); if (_month == 12) { _month = 1; _year += 1; } else _month += 1; } return *this; } Date operator-(int day) { Date d(*this); d._day -= day; while (d._day <= 0) { if (d._month == 1) { d._month = 12; d._year -= 1; } else d._month -= 1; d._day += DayInMonth(); } return d; } bool operator>(const Date& d) { if(_year > d._year) return true; if(_year == d._year) { if(_month > d._month) return true; if(_month == d._month) { if(_day > d._day) { return true; } } } return false; } bool operator==(const Date& d) { if((_year == d._year) &&(_month == d._month) &&(_day == d._day)) { return true; } return false; } bool operator>=(const Date& d) { return ((*this > d) || (*this == d)); } bool operator!=(const Date& d) { return !(*this == d); } int operator-(Date&d) { int days=0; Date d1(d); Date d2(*this); if (d1 > d2) { d1 = (*this); d2 = d; } while (d1 != d2) { days++; d1 += 1; } return days; } int DayInMonth() { int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (((_year % 4 == 0) && (_year % 100 != 0) || (_year & 400 == 0))) { days[2] = 29; } return days[_month]; } bool IsRightDay() { if (_year < 1900) { return true; } if (_month<1 || _month>12) { return true; } if (_day<1 || _day>DayInMonth()) { return true; } return false; } private: int _year; int _month; int _day; }; ostream& operator<<(ostream&os, Date&d) { os << d._year << "-" << d._month << "-" << d._day << endl; return os; } int main() { Date d1(1994, 5, 25); Date d2 = d1 + 31; Date d3(2016, 3, 14); Date d4 = d3 - 31; cout << d1 << endl; cout << d2 << endl; cout << d4 << endl; cout << d3 - d1 << endl; system("pause"); return 0; }