Overloading for Both Pre and Post Increment: Resolving Ambiguity
Operators can be overloaded in C to extend the functionality of built-in operators for user-defined types. One common use case is overloading the increment operator ( ) for both pre- and post-increment operations. However, achieving this without encountering ambiguity issues is a challenge.
Initial Approach: Same Return Type
In the code snippet provided, the initial attempt overloads the operator with the same return type (int) for both pre- and post-increment. However, this approach fails due to the following reasons:
Solution: Overloading with Dummy Argument
To resolve this ambiguity, the postfix version of the operator is overloaded with a dummy int parameter. This modification accomplishes two goals:
Code Example:
<code class="cpp">#include <iostream> class CSample { public: int m_iValue; // just to directly fetch inside main() CSample() : m_iValue(0) {} CSample(int val) : m_iValue(val) {} // Overloading ++ for Pre-Increment CSample& operator++() { ++m_iValue; return *this; } // Overloading ++ for Post-Increment CSample operator++(int) { CSample tmp(*this); operator++(); // prefix-increment this instance return tmp; // return value before increment } }; int main() { CSample obj1(5); std::cout << obj1.m_iValue << std::endl; // Output: 5 // Pre-Increment ++obj1; std::cout << obj1.m_iValue << std::endl; // Output: 6 // Post-Increment CSample obj2 = obj1++; std::cout << obj2.m_iValue << std::endl; // Output: 6 std::cout << obj1.m_iValue << std::endl; // Output: 7 return 0; }</code>
By overloading the operator with a dummy argument for the postfix version, we effectively resolve the ambiguity and enable both pre- and post-increment behavior for custom types in C .
The above is the detailed content of How to Overload the Increment Operator ( ) for Both Pre and Post-Increment in C ?. For more information, please follow other related articles on the PHP Chinese website!