Define a class, DATE, including current year, month and day. You may search in MSDN with keywords "tm" to know how to get the current date. Define a derived class BIRTHDAY of DATE, saving someone's birthday with year, month and day. The programmer can call the member function AGE to get someone's age as follows:
int main
{
BIRTHDAY Zhang(1988, 5, 2);
cout << Zhang.AGE() << endl; // Now Zhang's age is 26.
return 0;
}
#include <iostream>
#include <time.h>
using namespace std;
class BIRTHDAY
{
private:
int _year;
int _month;
int _day;
public:
BIRTHDAY(int year, int month, int day);
int AGE();
};
BIRTHDAY::BIRTHDAY(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
int BIRTHDAY::AGE()
{
time_t tt = time(NULL);
tm* t = localtime(&tt);
return t->tm_year - _year + 1900;
}
int main()
{
BIRTHDAY Zhang(1988, 5, 2);
cout << Zhang.AGE() << endl; // Now Zhang's age is 26.
getchar();
return 0;
}