运算符++中的Int参数 [英] Int Argument in operator++

查看:236
本文介绍了运算符++中的Int参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class myClass
{
    public:

    void operator++()
    {
        // ++myInstance.
    }

    void operator++(int)
    {
        // myInstance++.
    }
}

除了允许编译器区分 myInstance ++ ++ myInstance 是<$ c $中的可选 int c> operator ++ 实际上什么?

Besides letting the compiler distinguish between myInstance++ and ++myInstance, is the optional int argument in operator++ actually for anything? If so, what is it?

推荐答案

正如@Konrad所说,int参数不用于任何东西,除了distingush

As @Konrad said, the int argument is not used for anything, other than to distingush between the pre-increment and post-increment forms.

请注意,您的运算符应该返回一个值。预增量应返回一个引用,后增量应返回值。机智:

Note however that your operators should return a value. Pre-increment should return a reference, and post-increment should return by-value. To wit:

class myClass
{

public:

myClass& operator++()
{
    // ++myInstance. 
    return * this;   
}
myClass operator++(int)
{
    // myInstance++.
    myClass orig = *this;
    ++(*this);  // do the actual increment
    return orig;
}
};



编辑:



正如Gene Bushuyev提到的正确地在下面,并不是绝对要求 operator ++ 返回非空值。然而,在大多数情况下(我不能想到一个例外),你需要。特别是如果你想把运算符的结果赋给一些其他的值,比如:

As Gene Bushuyev mentions correctly below, it is not an absolute requirement that operator++ return non-void. However, in most cases (I can't think of an exception) you'll need to. Especially if you want to assign the results of the operator to some other value, such as:

myClass a;
myClass x = a++;



EDIT2:



postimcrement版本,你将在对象递增之前返回。这通常使用本地临时实现。见上文。

Also, with the postimcrement version, you will return the object before it was incremented. This is typically done using a local temporary. See above.

这篇关于运算符++中的Int参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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