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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | // Code derived from Stroustrup's PPP2 book
// § 9.7.5 Members and “helper functions”
// -and beginning on p 332
#include <iostream>
using namespace std;
enum class Month {
jan = 1,
feb,
mar,
apr,
may,
jun,
jul,
aug,
sep,
oct,
nov,
dec
};
class Date {
public:
Date(int yy, Month mm, int dd) : y{yy}, m{mm}, d{dd} {}
int day() const { return d; }
Month month() const { return m; }
int year() const { return y; }
private:
int y; // year
Month m;
int d; // day of month
};
//------------------------------------------------------------------------------
// Here are some examples of helper functions:
Date next_Sunday(const Date& d)
{ // bogus stub
// access d using d.day(), d.month(), and d.year()
// make new Date to return
return d;
}
Date next_weekday(const Date& d) { return d; }
bool leapyear(int d, int m, int y)
{ // bogus stub
cout << d << m << y << '\n'; // rm's 'unused variable' error
return false;
}
bool operator==(const Date& a, const Date& b)
{
return a.year() == b.year() && // bogus stub
a.month() == b.month() && //
a.day() == b.day();
}
bool operator!=(const Date& a, const Date& b) { return ! (a == b); }
//------------------------------------------------------------------------------
namespace Chrono {
enum class Month { // this is the one inside the Chrono:: scope (and &tc.)
jan = 1,
feb,
mar,
apr,
may,
jun,
jul,
aug,
sep,
oct,
nov,
dec
};
class Date {
public:
Date() : y{2001}, m{Month::jan}, d{1} {}
Date(int yy, Month mm, int dd) : y{yy}, m{mm}, d{dd} {}
int day() const { return d; }
Month month() const { return m; }
int year() const { return y; }
private:
int y; // year
Month m;
int d; // day of month
};
bool is_date(int y, Month m, int d); // true for valid date
Date next_Sunday(const Date& d) { return d; }
Date next_weekday(const Date& d) { return d; }
// see chapter 9, exercise 10
bool leapyear([[maybe_unused]] int y) { return false; }
bool operator==(const Date& a, const Date& b)
{ // bogus stub
cout << a.year() << b.year() << '\n'; // rm's 'unused variable' error
return false;
}
// ...
} // namespace Chrono
//------------------------------------------------------------------------------
int main()
{
Date d{2008, Month::feb, 23};
[[maybe_unused]] bool is_different = next_Sunday(d) != next_weekday(d);
Chrono::Date dd;
}
|
build & run:
g++ -std=c++20 -O2 -Wall -pedantic ./ch_09/main_p332.cpp && ./a.out