If you’re writing a class that is numeric or pointery, then it needs:
++obj
)
obj++
)
--obj
)
obj--
)
None of these come for free. You have to write them all.
Preincrement is easy:
Whatever &operator++() { // No argument means preincrement // Do what is needed to change the object // which might be *this += 1; return *this; }
Fast & efficient—no copying is required.
Postincrement is harder, but can be the same for nearly all classes:
Whatever operator++(int) { // Dummy int arg means postincrement const auto save = *this; ++*this; // Call the preincrement method return save; }
Less efficient—need to make a copy, and return by value.
Pre-/post-decrement is essentially the same. Get pre-/post-increment working, and then (I can’t believe that I’m saying this) use copy & paste.
operator++
should use operator+=
to accomplish
the increment. Less duplication of information—good!
Modified: 2017-02-22T15:49 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |