https://rentry.org/PPP2_p321

// Code derived from Stroustrup's PPP2 book
// § 9.6 Operator overloading
//  -and beginning on p 321

#include <iostream>
#include <string>
#include <vector>

using namespace std;

enum class Month {
  Jan = 1,
  Feb,
  Mar,
  Apr,
  May,
  Jun,
  Jul,
  Aug,
  Sep,
  Oct,
  Nov,
  Dec
};

// prefix increment operator
Month operator++(Month& m)
{
  // The ? : construct is called an “arithmetic if” (AKA 'ternary conditional')
  m = (m == Month::Dec) ? Month::Jan  // “wrap around”
                        : Month{int(m) + 1};

  return m;
}

const vector<string> month_tbl{"January",   "February", "March",    "April",
                               "May",       "June",     "July",     "August",
                               "September", "October",  "November", "December"};

ostream& operator<<(ostream& os, Month m)
{
  return os << month_tbl[int(m) - 1];
}

int main()
{
  Month m = Month::Sep;
  ++m;  // m becomes Oct
  ++m;  // m becomes Nov
  ++m;  // m becomes Dec
  ++m;  // m becomes Jan ("wrap around")

  cout << m << '\n';
}

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

class Vector {};

// int    operator+(int, int);  // error: you can't overload built-in +
Vector operator+(const Vector&, const Vector&);  // OK
Vector operator+=(const Vector&, int);           // OK

build & run:

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

PrevUpNext

Edit
Pub: 06 Apr 2023 17:36 UTC
Edit: 03 May 2023 01:14 UTC
Views: 598