如何重载操作符++在两种不同的方式后缀a ++和前缀++ a? [英] How to overload the operator++ in two different ways for postfix a++ and prefix ++a?

查看:142
本文介绍了如何重载操作符++在两种不同的方式后缀a ++和前缀++ a?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以两种不同的方式重载操作符++,用于后缀 a ++ 和前缀 ++ a

How to overload the operator++ in two different ways for postfix a++ and prefix ++a?

推荐答案

应如下所示:

class Number 
{
    public:
        Number& operator++ ()     // prefix ++
        {
           // Do work on this.   (increment your object here)
           return *this;
        }

        // You want to make the ++ operator work like the standard operators
        // The simple way to do this is to implement postfix in terms of prefix.
        //
        Number  operator++ (int)  // postfix ++
        {
           Number result(*this);   // make a copy for result
           ++(*this);              // Now use the prefix version to do the work
           return result;          // return the copy (the old) value.
        }
}; 

这篇关于如何重载操作符++在两种不同的方式后缀a ++和前缀++ a?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆