How can I overload the prefix and postfix forms of operators ++ and --

本文介绍了如何在C++中重载前缀和后缀形式的++和--运算符。通过定义不同返回类型的成员函数实现,前缀版本返回引用,后缀版本返回值。文章还提供了具体的代码示例说明了如何使用这些重载运算符。
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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值