1. 程式人生 > >c++類的單目和雙目運算子的重定義

c++類的單目和雙目運算子的重定義

這個裡面需要注意的是對於雙目運算子,像是加號,如果是複數加整數是一種情況,而整數加複數又是另一種情況,所以需要重定義兩次。

而對於單目運算子,如果是字首的,直接重定義就可以了,但是如果是字尾的,我們在宣告的時候,加上一個 int 就行了。

#include <iostream>
using namespace std;
 
class Date
{
	public :
		Date() {
			year=0;
			month=0;
			day=0;
		}
		Date(int y,int m,int d)
		{
			year = y;
			month = m;
			day = d;
		}
		void display()
		{
			cout<<year<<"/"<<month<<"/"<<day<<endl;
		}
		friend Date operator+(int i, Date c);
		friend Date operator+(Date c, int i);
		Date operator++();
		Date operator++(int);
	  private:
		int year,month,day;
};
 
Date Date::operator++()
{
	if (day+1>30) {
		day %= 30;
		if (month+1>12) {
			month %= 12;
			year++;
		}
	}
	else
		day++;
	return *this;
}
 
Date Date::operator++(int)
{
	Date temp(*this);
	if (day+1>30) {
		day %= 30;
		if (month+1>12) {
			month %= 12;
			year++;
		}
	}
	else
		day++;
	return temp;
}
 
Date operator+(int i,Date c)
{
	int year_add = i / 360;
	int month_add = i / 30;
	int day_add = i % 30;
	c.year += year_add;
	c.month = c.month + month_add % 12;
	if (c.month>12)
		c.month -= 12;
	c.day = c.day+day_add % 30;
	if (c.day>30)
		c.day -= 30;
	return c;
}
 
Date operator+(Date c,int i)
{
	int year_add = i / 360;
	int month_add = i / 30;
	int day_add = i % 30;
	c.year += year_add;
	c.month = c.month + month_add % 12;
	if (c.month>12)
		c.month -= 12;
	c.day = c.day+day_add % 30;
	if (c.day>30)
		c.day -= 30;
	return c;
}
 
int main()
{
	Date a(2018,3,10),b;
	int num=1000;
	b=a+num;
	b.display();
	++b;
	b.display();
	a = b++;
	a.display();
	b.display();
	system("pause");
	return 0;
}