十二.单目运算符重载(C++)

内容参考于《21天学通C++》(第八版)
不去纠结C++的原理和细节,从C的角度去学习C++,再通过C++项目去加深理解

十二.单目运算符重载

1. 示例
#include <iostream>
using namespace std;
class Date
{
private:
	int day, month, year;

public:
	Date(int inMonth, int inDay, int inYear)
		: month(inMonth), day(inDay), year(inYear) {};

	Date & operator ++ () // prefix increment
	{
		++day;
		return *this;
	}

	Date & operator -- () // prefix decrement
	{
		--day;
		return *this;
	}

	void DisplayDate()
	{
		cout << month << " / " << day << " / " << year << endl;
	}
};

int main()
{
	Date holiday(12, 25, 2016); // Dec 25, 2016

	cout << "The date object is initialized to: ";
	holiday.DisplayDate();

	++holiday; // move date ahead by a day
	cout << "Date after prefix-increment is: ";
	holiday.DisplayDate();

	--holiday; // move date backwards by a day
	cout << "Date after a prefix-decrement is: ";
	holiday.DisplayDate();

	return 0;
}

运行结果

The date object is initialized to: 12 / 25 / 2016
Date after prefix-increment is: 12 / 26 / 2016
Date after a prefix-decrement is: 12 / 25 / 2016
2. 转换运算符
cout << holiday; // error in absence of conversion operator

将导致这样的编译错误: error: binary ‘<<’ : no operator found which takes a right-hand operand of type ‘Date’ (or there is no acceptable conversion)。这种错误表明, cout 不知道如何解读 Date 实例,因为 Date类不支持这样的运算符,即将 Date 对象的内容转换成 cout 能够接受的类型。然而, cout 能够很好地显示 const char*:
因此,要让 cout 能够显示 Date 对象,只需添加一个返回 const char*的运算符:

#include <iostream>
#include <sstream> // new include for ostringstream
#include <string>
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) {};

	operator const char*()
	{
		ostringstream formattedDate; // assists string construction
		formattedDate << month << " / " << day << " / " << year;

		dateInString = formattedDate.str();
		return dateInString.c_str();
	}
};

int main()
{
	Date Holiday(12, 25, 2016);

	cout << "Holiday is on: " << Holiday << endl;

	// string strHoliday (Holiday); // OK!
		// strHoliday = Date(11, 11, 2016); // also OK!

	return 0;
}

运行结果

Holiday is on: 12 / 25 / 2016
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值