1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <iostream>
#include <string>
class Date
{
private:
int year;
int month;
int day;
public:
// ctor(s)
Date()
: year(1), month(1), day(1) { }
Date(int y, int m, int d)
: year(y), month(m), day(d) { }
// I/O functions
void input();
void output() const;
// declare operator<< as a friend so it can "see" the private data members
// and output to the passed std::ostream (usually std::cout)
friend std::ostream& operator<<(std::ostream&, Date);
// getters/setters
// declare the getters as const so the member funcs can't alter the data members
int getYear() const { return year; }
void setYear(int y) { year = y; }
int getMonth() const { return month; }
void setMonth(int m) { month = m; }
int getDay() const { return day; }
void setDay(int d) { day = d; }
};
int main()
{
Date myDate;
myDate.input();
myDate.output();
Date anotherDate(2007, 2, 25);
anotherDate.output();
// with operator<< overloaded output of a class is as easy as
// Plain Old Data like an int
std::cout << myDate << '\n';
std::cout << anotherDate << '\n';
}
void Date::input()
{
std::cout << "Enter the new year: ";
int y;
std::cin >> y;
year = y;
std::cout << "Enter the new month: ";
int m;
std::cin >> m;
month = m;
std::cout << "Enter the new day: ";
int d;
std::cin >> d;
day = d;
}
void Date::output() const
{
std::cout << day << ' ';
std::string months[12] = { "January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December" };
std::cout << months[month] << ' ' << year << '\n';
}
// let's chain the output into cout
std::ostream& operator<<(std::ostream& os, Date d)
{
os << d.day << ' ';
std::string months[12] = { "January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December" };
os << months[d.month] << ' ' << d.year;
return os;
}
| |