C++ Program to implement Operator Overloading with Unary Operators (++, –) – Q16
Q16. Program to implement Operator Overloading with Unary Operators (++, –):
Define a DATE class with month, day & year as the private data member.
Implement Operator Overloading for finding the next day of given date.
… from College notes (BCA/MCA assignments):
#include <iostream.h> #include <conio.h> class CDATE{ private: int dd, mm, yy; int _days; static int months[12]; public: void Init(){ cout<<"\n Enter a Date (dd mm yyyy): "; cin>>dd>>mm>>yy; } void operator++(){ _days = DaysThisMonth(mm, yy); if(dd >=_days){ if(mm >= 12){ yy += 1; mm = 1; } else mm += 1; dd = 1; } else dd += 1; cout<<"\n Next Date: "<<dd<<":"<<mm<<":"<<yy; } int DaysThisMonth(int, int); }; int CDATE :: months[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int CDATE :: DaysThisMonth(int mm, int yy){ if (mm != 2) return months[mm-1]; if (yy % 4) // Not leap year return 28; if (yy % 100) // It is leap year return 29; if (yy % 400) // Not leap year return 28; return 29; // It is leap year } void main(){ CDATE dt; clrscr(); dt.Init(); char ch; while(ch != 'y'){ ++dt; cout<<"\t\t\t Quit (y/n) ?: "; cin>>ch; } cout<<"\n\n Press Any Key to Exit ..."; getch(); }
Output:
Enter a Date (dd mm yyyy): 26 12 2003
Next Date: 27:12:2003 Quit (y/n) ?: n
Next Date: 28:12:2003 Quit (y/n) ?: n
Next Date: 29:12:2003 Quit (y/n) ?: n
Next Date: 30:12:2003 Quit (y/n) ?: n
Next Date: 31:12:2003 Quit (y/n) ?: n
Next Date: 1:1:2004 Quit (y/n) ?: n
Next Date: 2:1:2004 Quit (y/n) ?: n
Next Date: 3:1:2004 Quit (y/n) ?: n
Next Date: 4:1:2004 Quit (y/n) ?: n
Next Date: 5:1:2004 Quit (y/n) ?: y
Press Any Key to Exit …