内容参考于《21天学通C++》(第八版)
不去纠结C++的原理和细节,从C的角度去学习C++,再通过C++项目去加深理解
十三.双目运算符重载
以类成员的方式实现的双目运算符只接受一个参数, 其原因是第二个参数通常是从类属性获得的。
1. 示例
#include <iostream>
using namespace std;
class Date
{
private:
int day, month, year;
string dateInString;
public:
Date(int inMonth, int inDay, int inYear)
: month(inMonth), day(inDay), year(inYear) {};
Date operator + (int daysToAdd) // binary addition
{
Date newDate(month, day + daysToAdd, year);
return newDate;
}
Date operator - (int daysToSub) // binary subtraction
{
return Date(month, day - daysToSub, year);
}
void DisplayDate()
{
cout << month << " / " << day << " / " << year << endl;
}
};
int main()
{
Date Holiday(12, 25, 2016);
cout << "Holiday on: ";
Holiday.DisplayDate();
Date PreviousHoliday(Holiday - 19);
cout << "Previous holiday on: ";
PreviousHoliday.DisplayDate();
Date NextHoliday(Holiday + 6);
cout << "Next holiday on: ";
NextHoliday.DisplayDate();
return 0;
}
运行结果
Holiday on: 12 / 25 / 2016
Previous holiday on: 12 / 6 / 2016
Next holiday on: 12 / 31 / 2016
2. 字符串拼接实质
MyString operator+ (const MyString& addThis)
{
MyString newString;
if (addThis.buffer != NULL)
{
newString.buffer = new char[GetLength() + strlen(addThis.buffer) + 1];
strcpy(newString.buffer, buffer);
strcat(newString.buffer, addThis.buffer);
}
return newString;
}