C++ 重载运算符


#include <iostream>
#include <string>
#include <sstream> 
#include <memory> 

using namespace std;

class Date
{
private:
	int day;
	int month;
	int year;
	string DateString;
public:
	Date(int year, int month, int day);
	Date & operator++();	/*	重载前缀加	*/ 
	Date & operator--();	/*	重载前缀减	*/
	Date operator++(int);	/*	重载后缀加	*/ 
	Date operator--(int);	/*	重载后缀减	*/
	operator const char*(); /*	重载类型转换运算符,内置的自动转换为char *,还可以有其它的类型转换运算符,如operator int	*/

	void operator+=(const int days){	this->day += days;	}
	void operator-=(const int days){	this->day -= days;	}
	bool operator==(const Date &date){	return date.day==this->day && date.month==this->month && date.year==this->year;	}
	bool operator!=(const Date &date){	return !((*this)==date);	}
};

Date::Date(int year, int month, int day)
{
	this->year = year;
	this->month = month;
	this->day = day;
}

/*	前缀加 先递增,然后返回当前对象的引用	*/ 
Date & Date::operator++()
{
	++day;
	return *this;
}

Date & Date::operator--()
{
	--day;
	return *this;
}

/*	后缀加,先复制当前对象,然后执行递增操作,再返回复制对象	*/ 
Date Date::operator++(int)
{
	Date temp(year,month,day);
	day++;
	return temp;
}

Date Date::operator--(int)
{
	Date temp(year,month,day);
	day--;
	return temp;
}

Date::operator const char*()
{
	ostringstream date;
	date<<year<<'-'<<month<<'-'<<day;

	DateString = date.str();

	return DateString.c_str();
}


int main()
{
	Date date(2012,5,1);
	Date date2(2012,5,25);

	date += 24;
	cout<<date<<endl;

	if (date == date2)
		cout<<"date == date2"<<endl;
	else
		cout<<"date != date2"<<endl;


	/*	智能指针类,在VS2012中编译通过,即支持C++11, 在Dev C++编译错误,不支持C++11	*/
	unique_ptr<Date> m(new Date(2000,1,1));
	cout<<*m<<endl;

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值