Hi
Please take a look at the following example:
Code:01 class Digit 02 { 03 private: 04 int m_nDigit; 05 public: 06 Digit(int nDigit=0) 07 { 08 m_nDigit = nDigit; 09 } 10 11 Digit& operator++(); // prefix 12 Digit& operator--(); // prefix 13 14 Digit operator++(int); // postfix 15 Digit operator--(int); // postfix 16 17 int GetDigit() const { return m_nDigit; } 18 }; 19 20 Digit& Digit::operator++() 21 { 22 // If our number is already at 9, wrap around to 0 23 if (m_nDigit == 9) 24 m_nDigit = 0; 25 // otherwise just increment to next number 26 else 27 ++m_nDigit; 28 29 return *this; 30 } 31 32 Digit& Digit::operator--() 33 { 34 // If our number is already at 0, wrap around to 9 35 if (m_nDigit == 0) 36 m_nDigit = 9; 37 // otherwise just decrement to next number 38 else 39 --m_nDigit; 40 41 return *this; 42 } 43 44 Digit Digit::operator++(int) 45 { 46 // Create a temporary variable with our current digit 47 Digit cResult(m_nDigit); 48 49 // Use prefix operator to increment this digit 50 ++(*this); // apply operator 51 52 // return temporary result 53 return cResult; // return saved state 54 } 55 56 Digit Digit::operator--(int) 57 { 58 // Create a temporary variable with our current digit 59 Digit cResult(m_nDigit); 60 61 // Use prefix operator to increment this digit 62 --(*this); // apply operator 63 64 // return temporary result 65 return cResult; // return saved state 66 } 67 68 int main() 69 { 70 Digit cDigit(5); 71 ++cDigit; // calls Digit::operator++(); 72 cDigit++; // calls Digit::operator++(int); 73 74 return 0; 75 }
I have three questions.
1) When overloading the postfix operators ++/--, we add the dummy integer variable. Is there any reason why postfix was chosen to need this dummy variable, and not the prefix?
2) When using x++ (where x is an instance of a class), then does the compiler automatically add the dummy integer? So it calls x++ as x.operator ++(0), e.g.?
3) When returning the *this-pointer, they use
Why do they include the &? We have had lengthy talks about this, and we agreed that *this is a pointer (by type), but acts like a reference. So personally I would not include the ampersand. What do you say?Code:Digit& operator++(); // prefix
Best,
Niles.



LinkBack URL
About LinkBacks




CornedBee