Int Argument in operator++

微笑、不失礼 提交于 2019-12-22 01:43:18

问题


class myClass
{
    public:

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

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

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


回答1:


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;
}
};

EDIT:

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:

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




回答2:


is the optional int argument in operator++ actually for anything?

No. The only purpose is to distinguish between the two overloads. Quite disappointing, I know. ;-)



来源:https://stackoverflow.com/questions/4659162/int-argument-in-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!