https://rentry.org/PPP2_p332

// 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

PrevUpNext

Edit
Pub: 06 Apr 2023 17:58 UTC
Edit: 03 May 2023 01:23 UTC
Views: 580