#include
#include
#include
using namespace std;
class cdate
bool isleapyear(int year); //判斷是否是閏年
int datetoon(const cdate &other); //日期轉換為從0年0月0日起的天數
int monthday(int year, int month); //當前月份有幾天
cdate operator +(const cdate &other); //兩個日期相加
int operator -(const cdate &other); //兩個日期相減的天數
cdate operator +(int nday); //當前日期加上nday天
cdate operator -(int nday); //當前日期減去nday天
private:
int m_year;
int m_month;
int m_day;
};bool cdate::isleapyear(int year)
int cdate::datetoon(const cdate &other)
}int sum_day;
switch(other.m_month) //計算本月一起共有多少天
sumday += sum_day;
sumday += other.m_day;
if(isleapyear(other.m_year) && other.m_month > 2)//當前年份是否是閏年
return sumday;
}int cdate::monthday(int year, int month)
else
break;
case 4:
case 6:
case 9:
curday = 30;
break;
default:;}
return curday;
}cdate cdate::operator+(const cdate &other)
temp.m_day = this->m_day + other.m_day;
if(temp.m_day > monthday(temp.m_year, temp.m_month)) //判斷當前天數是否大於本月的天數
return temp;
}int cdate::operator-(const cdate &other)
cdate cdate::operator+(int nday)
}if(days > 0 && days <=31) //判斷幾月幾日
else if(days <= 59)
else if(days <= 90)
else if(days <= 120)
else if(days <= 151)
else if(days <= 181)
else if (days <= 212)
else if( days <= 243)
else if (days <= 273)
else if(days <= 304)
else if (days <= 334)
else
cdate dest = *this + temp; //呼叫兩個年份相加運算子構造最終物件
return dest;
}cdate cdate::operator-(int nday)
}if(isleapyear(this->m_year- nyear - 1)) //判斷多減去的那一年是否是閏年
else
cdate dest = temp + nd; //呼叫加乙個整形天數運算子過載函式計算最終cdate物件
return dest;
}ostream &operator<<(ostream &os, const cdate &other)
int main()
/*the first date object is :1990--5--2
the days between (0, 0, 0 ) and first date has :726985 days
the second date object is :1988--4--6
the first date + second date is : 3978--9--8
the first date - second date has: 726 days
after the first date2 + 726 days the date is :1990--5--2
after the first date - 726 days the date is :1988--6--7
請按任意鍵繼續. . .
c pair 加減運算子過載
c pair物件沒有定義加減運算子,每次相加減太麻煩,寫乙個放在這裡,做題需要時複製乙個。另外,pari物件是可以直接使用比較運算子 pair相加 templateinline const pairoperator const pair p1,const pair p2 pair相減 templat...
運算子過載 賦值運算子的過載
有時候希望賦值運算子兩邊的型別可以不匹配,比如,把乙個int型別變數賦值給乙個complex物件,或把乙個 char 型別的字串賦值給乙個字串物件,此時就需要過載賦值運算子 注意 賦值運算子 只能過載為成員函式 賦值運算子過載例項示例 include include using namespace ...
運算子過載 類的賦值運算子過載
下面介紹類的賦值運算子 1.c 中物件的記憶體分配方式 在c 中,物件的例項在編譯的時候,就需要為其分配記憶體大小,因此,系統都是在stack上為其分配記憶體的。這一點和c 完全不同!千 萬記住 在c 中,所有類都是reference type,要建立類的實體,必須通過new在heap上為其分配空間...