// This code illustrates implementing the preincrement and postincrement // operators in a class. // // Notes: // • The letters[] array should really be static. As it is, there's // a copy of it in each Greek object. // • preincrement returns by reference, because that’s faster than // making a copy of the Greek object. // • preincrement uses the C++17 free function size(), which returns // the number of elements in letters (24). DRY! // • postdecrement returns by value, which is slower. However, it’s // returning a copy, so it can’t return by reference, because that // copy vanishes when the method returns. // • Postincrement is implemented ENTIRELY in terms of preincrement. // This technique can be used in almost any class that implements // postincrement. // • operator<< does NOT have to be a friend. It just uses the // public accessor str(). #include #include using namespace std; class Greek { unsigned short state{0}; // index to current greek letter const string letters[24] { "α","β","γ","δ","ε","ζ","η","θ","ι","κ","λ","μ", "ν","ξ","ο","π","ρ","σ","τ","υ","φ","χ","ψ","ω"}; public: const string &str() const { return letters[state]; // return reference to const string } Greek& operator++() { // No argument means pre-increment. if (++state >= size(letters)) // Went past ω, the last letter? state = 0; // Wrap around to α, the first letter. return *this; // Return reference to current object. } Greek operator++(int) { // The (int) means post-increment. const auto save = *this; // Save the state before incrementing. ++*this; // Let pre-increment do the work. return save; // Return local variable BY VALUE. } }; ostream& operator<<(ostream &os, const Greek &rhs) { return os << rhs.str(); // Just use the public getter. } int main() { Greek g, h; // αβγδεζηθικλμνξοπρστυφχψω for (int i=0; i<50; i++) cout << ++g; // preincrement, so start with β cout << '\n'; for (int i=0; i<50; i++) cout << h++; // postincrement, so start with α cout << '\n'; }