https://rentry.org/PPP2_p324

// Code derived from Stroustrup's PPP2 book
// § 9.7.1 Argument types
//  -and beginning on p 324

enum class Month {
  jan = 1,
  feb,
  mar,
  apr,
  may,
  jun,
  jul,
  aug,
  sep,
  oct,
  nov,
  dec
};

// simple Date (use Month type)
class Date {
 public:
  Date(int y, Month m, int d);  // check for valid date and initialize

  // . . .

  int   year() { return y; }
  Month month() { return m; }
  int   day() { return d; }

 private:
  int   y;  // year
  Month m;
  int   d;  // day
};

Date::Date(int yy, Month mm, int dd) : y{yy}, m{mm}, d{dd} {}

int main()
{
  // Date d1{4, 5, 2005};  // oops: year 4, day 2005
  // Date d2{2005, 4, 5};  // April 5 or May 4?

  // Date dx1{1998, 4, 3};            // error: 2nd argument not a Month
  // Date dx2{1998, 4, Month::mar};   // error: 2nd argument not a Month
  // Date dx2{4, Month::mar, 1998};   // oops: run-time error: day 1998
  // Date dx2{Month::mar, 4, 1998};   // error: 2nd argument not a Month
  Date dx3{1998, Month::mar, 30};  // OK
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_09/main_p324.cpp && ./a.out

PrevUpNext

Edit
Pub: 06 Apr 2023 17:39 UTC
Edit: 03 May 2023 01:15 UTC
Views: 583