运算符++中的Int Argument

Max*_*xpm 16 c++ arguments class operator-overloading

class myClass
{
    public:

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

    void operator++(int)
    {
        // myInstance++.
    }
}
Run Code Online (Sandbox Code Playgroud)

让编译器区分myInstance++++myInstance,实际上是什么可选int参数operator++?如果是这样,它是什么?

Joh*_*ing 18

正如@Konrad所说,int参数不用于任何东西,除了在pre-increment和post-increment表单之间进行distingush.

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

class myClass
{

public:

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

编辑:

正如Gene Bushuyev在下面正确提到的那样,并非绝对要求operator++返回非虚空.但是,在大多数情况下(我不能想到例外)你需要.特别是如果要将运算符的结果分配给其他值,例如:

myClass a;
myClass x = a++;
Run Code Online (Sandbox Code Playgroud)

EDIT2:

此外,使用postimcrement版本,您将在对象增加之前返回该对象.这通常使用本地临时完成.往上看.


Kon*_*lph 12

实际上对于任何东西都是operator ++中的可选int参数?

不.唯一的目的是区分两个重载.我知道,非常令人失望.;-)