一道sicily练习题,总是wrong answer
题目:
Implement the operator +=, -=, +, -, in the class Date
class Date
{
public:
Date(int y=0, int m=1, int d=1);
static bool leapyear(int year);
int getYear() const;
int getMonth() const;
int getDay() const;
// add any member you need here
};
You implementation should enable the usage like this:
void f()
{
Date date = d;
cout << "date = " << date << endl;
cout << "date+1 = " << date+1 << endl;
cout << "date-1 = " << date-1 << endl;
date+=366;
cout << "date = " << date << endl;
date-=365;
cout << "date = " << date << endl;
date-=-365;
cout << "date = " << date << endl;
date+=-366;
cout << "date = " << date << endl;
cout << endl;
}
The output of f() should be:
date = 2004-2-28
date+1 = 2004-2-29
date-1 = 2004-2-27
date = 2005-2-28
date = 2004-2-29
date = 2005-2-28
date = 2004-2-28
提交时不需要提交operator << 重载。
我的代码:
输出答案和给出的结果一样,但就是wrong answer……郁闷
#include<iostream>#include<string.h>using namespace std;class Date{public: Date(int y=0, int m=1, int d=1); static bool leapyear(int year); int& operator [](const char* strTag) { if (strcmp(strTag,"year")==0) { return year; } else if (strcmp(strTag,"month")==0) { return month; } else if (strcmp(strTag,"day")==0) { return day; } } Date& operator =(Date& d) { this->year=d.year; this->month=d.month; this->day=d.day; return *this; } Date& operator +=(int d); Date& operator -=(int d); Date& operator +(int d); Date& operator -(int d); Date& operator --() { *this-=1; return *this+1; } Date& operator ++() { *this+=1; return *this-1; } Date& operator --(int) { *this-=1; return *this; } Date& operator ++(int) { *this+=1; return *this; } bool operator >(Date d) { if(this->year>d.year) { return true; } else if(this->month>d.month) { return true; } else if(this->day>d.day) { return true; } else { return false; } } bool operator >=(Date d) { return !(*this<d); } bool operator <(Date d) { if(this->year<d.year) { return true; } else if(this->month<d.month) { return true; } else if(this->day<d.day) { return true; } else { return false; } } bool operator <=(Date d) { if(this->year<=d.year) { return true; } else if(this->month<=d.month) { return true; } else if(this->day<=d.day) { return true; } else { return false; } } bool operator ==(Date d) { if(this->year==d.year) { if(this->month==d.month) { if(this->day==d.day) { return true; } } } else { return false; } } bool operator !=(Date d) { if(this->year!=d.year) { return true; } else if(this->month!=d.month) { return true; } else if(this->day!=d.day) { return true; } else { return false; } } int getYear() const; int getMonth() const; int getDay() const; private: int year; int month; int day; // add any member you need here };Date D;Date& Date::operator +=(int d){ int t=d; if(t<0) { t=-t; *this=*this-t; } else { *this=*this+t; } return *this;}Date& Date::operator -=(int d){ int t=d; if(t<0) { t=-t; *this=*this+t; } else { *this=*this-t; } return *this;}