Witam,
poniższy kod działa tak jak powinien ale zastanawiam się czy nie lepiej by było, aby funkcja year() z klasy Date zwracała typ Year zamiast int.
Jeśli byłoby to lepsze rozwiązanie to może ktoś podpowiedzieć jak to zrobić? Problem sprawia mi operator << którym próbuję tą składową wyświetlić gdy funkcja Date::year zwraca Year.
class Year {
static const int min = 1800;
static const int max = 2200;
int y;
public:
class Invalid { };
Year(int y);
int year() const { return y; }
};
Year::Year(int y)
: y(y)
{
if (y < min || y > max) throw Invalid();
}
class Date {
public:
class Invalid { };
enum Month {
jan=1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
};
Date(Year y, Month m, int d);
void add_day(int n);
Month month() const { return m; }
int day() const { return d; }
int year() const { return y.year(); }
private:
Year y;
Month m;
int d;
bool check();
};
Date::Date(Year y, Month m, int d)
: y(y), m(m), d(d)
{
if (!check()) throw Invalid();
}
bool Date::check()
{
if (m < 1 || m > 12 || d < 1 || d > 31) return false;
return true;
}
void Date::add_day(int n)
{
d += n;
}
ostream& operator<<(ostream& os, const Date& dd)
{
return os << '(' << dd.year()
<< ',' << dd.month()
<< ',' << dd.day() << ')';
}
int main()
try {
Date today(1978, Date::jul, 20);
Date tomorrow = today;
tomorrow.add_day(1);
cout << today << endl;
cout << tomorrow << endl;
}
catch (Date::Invalid) {
cout << "Niepoprawna data\n";
return 1;
}