十三.双目运算符重载(C++)

内容参考于《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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值