https://rentry.org/PPP2_p364

// Code derived from Stroustrup's PPP2 book
// § 10.8 User-defined output operators
//  -and beginning on p 364

#include <iostream>

using namespace std;

//------------------------------------------------------------------------------

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

  Date() {}  // default constructor
  Date(int yy, Month mm, int dd) : y{yy}, m{mm}, d{dd} {}  // parm'd constructor

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

 private:
  int   y;
  Month m;
  int   d;
};

ostream& operator<<(ostream& os, const Date& d)
{
  return os << '(' << d.year()   //
            << ',' << d.month()  //
            << ',' << d.day()    //
            << ')';
}

int main()
{
  Date d1{1994, Date::mar, 29};
  Date d2{2000, Date::feb, 15};

  cout << d1 << '\n';

  // the same as operator<<(cout,d1) << '\n';
  operator<<(cout, d1) << '\n';

  // the same as operator<<(cout,d1) << d2 << '\n';
  cout << d1 << d2 << '\n';

  // the same as operator<<(operator<<(cout,d1),d2) << '\n';
  operator<<(operator<<(cout, d1), d2) << '\n';
}

build & run:

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

PrevUpNext

Edit
Pub: 07 Apr 2023 22:28 UTC
Edit: 03 May 2023 10:06 UTC
Views: 534