我正在努力解决Bjarne Stroustrups原理与实践第2版的第4钻。由于某种原因,它不会让我讨论我之前初始化的月份和年份成员。我知道有使用枚举器的替代方法,但我想知道如何使用它。有人可以帮助我吗?干杯
// Philipp Siedler
// Bjarne Stroustrup's PPP
// Chapter 9 Drill 4
#include "std_lib_facilities.h"
class Year {
static const int min = 1800;
static const int max = 2200;
private:
int y;
public:
class Invalid {};
Year(int x) : y{ x } { if (x < min || max <= x) throw Invalid{}; };
int year() { return y; };
};
enum class Month {
jan = 1, feb, march, apr, may, jun, jul, aug, sep, oct, nov, dec
};
class Date {
private:
Year y;
Month m;
int d;
public:
Date(Year y, Month m, int d) : y(y), m(m), d(d) {};
Year year() { return Year{ y }; };
Month month() { return Month{ m }; };
int day() { return d; };
void add_day(int n);
};
void Date::add_day(int n) {
d += n;
}
int main()
try
{
Date today{ Year{ 1978 }, Month::jun, 25 };
Date tomorrow = today;
tomorrow.add_day(1);
cout << "Year: " << today.year() << " Month: " << today.month() << " Day: " << today.day() << "\n";
cout << "Year: " << tomorrow.year() << " Month: " << tomorrow.month() << " Day: " << tomorrow.day() << "\n";
keep_window_open();
}
catch (runtime_error e) {
cout << e.what() << '\n';
keep_window_open();
}
catch (...) {
cout << "Exiting" << '\n';
keep_window_open();
}
答案 0 :(得分:0)
您好我自己已经弄清楚了,所以谁需要帮助解决同样的问题,这里有一个潜在的解决方案和操作符重载的简单示例:
// Philipp Siedler
// Bjarne Stroustrup's PPP
// Chapter 9 Drill 4
#include "std_lib_facilities.h"
class Date {
public:
enum Month {
jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
};
Date(int y, Month m, int d);
void add_day(int n);
int year() const { return y; }
Month month() const { return m; }
int day() const { return d; }
private:
int y;
Month m;
int d;
};
Date::Date(int y0, Date::Month m0, int d0) {
d = d0;
m = m0;
y = y0;
}
void Date::add_day(int n) {
d += n;
}
static ostream & operator<< (ostream & os, const Date::Month & m) {
switch (m) {
case Date::jan: os << "January"; break;
case Date::feb: os << "February"; break;
case Date::mar: os << "March"; break;
case Date::apr: os << "April"; break;
case Date::may: os << "May"; break;
case Date::jun: os << "June"; break;
case Date::jul: os << "July"; break;
case Date::aug: os << "August"; break;
case Date::sep: os << "September"; break;
case Date::oct: os << "October"; break;
case Date::nov: os << "November"; break;
case Date::dec: os << "December"; break;
}
return os;
}
ostream & operator<< (ostream & os, const Date & dd) {
os << "Year: " << dd.year() << " Month: " << dd.month() << " Day: " << dd.day() << endl;
return os;
}
int main()
try
{
Date today{ 1978, Date::jun, 25 };
Date tomorrow = today;
tomorrow.add_day(1);
cout << today;
cout << tomorrow;
keep_window_open();
}
catch (runtime_error e) {
cout << e.what() << '\n';
keep_window_open();
}
catch (...) {
cout << "Exiting" << '\n';
keep_window_open();
}