How can I overload the prefix and postfix forms of operators ++ and --? Via a dummy parameter. Since the prefix and postfix ++ operators can have two definitions, the C++ language gives us two different signatures. Both are called operator++(), but the prefix version takes no parameters and the postfix version takes a dummy int. (Although this discussion revolves around the ++ operator, the -- operator is completely symmetric, and all the rules and guidelines that apply to one also apply to the other.) class Number { public: Number& operator++ (); // prefix ++ Number operator++ (int); // postfix ++ }; Note the different return types: the prefix version returns by reference, the postfix version by value. If that's not immediately obvious to you, it should be after you see the definitions (and after you remember that y = x++ and y = ++x set y to different things). Number& Number::operator++ () { ... return *this; } Number Number::operator++ (int) { Number ans = *this; ++(*this); // or just call operator++() return ans; } The other option for the postfix version is to return nothing: class Number { public: Number& operator++ (); void operator++ (int); }; Number& Number::operator++ () { ... return *this; } void Number::operator++ (int) { ++(*this); // or just call operator++() } However you must *not* make the postfix version return the 'this' object by reference; you have been warned. Here's how you use these operators: Number x = /* ... */; ++x; // calls Number::operator++(), i.e., calls x.operator++() x++; // calls Number::operator++(int), i.e., calls x.operator++(0) Assuming the return types are not 'void', you can use them in larger expressions: Number x = /* ... */; Number y = ++x; // y will be the new value of x Number z = x++; // z will be the old value of x
How can I overload the prefix and postfix forms of operators ++ and --
本文介绍了如何在C++中重载前缀和后缀形式的++和--运算符。通过定义不同返回类型的成员函数实现,前缀版本返回引用,后缀版本返回值。文章还提供了具体的代码示例说明了如何使用这些重载运算符。

被折叠的 条评论
为什么被折叠?



