Is it allowed to name the parameter in postfix ope

2020-02-27 02:34发布

问题:

I am not using this code in any production environment, it is just for my understanding. Is this code valid (i.e. can I define my postfix operator like this?):

class A
{
public:
    A& operator++(int n)
    {
        std::cout<<"N is:"<<n<<"\n";
        return *this;
    }
};


int main()
{   
    A a;
    a++;
    a.operator ++(10);
}

On VS2008, I get the output as:

N is 0

for first call and

N is 10

for second call

回答1:

This behavior is legal and well defined in 13.5.7:

Calling operator++ explicitly, as in expressions like a.operator++(2), has no special properties: The argument to operator++ is 2.



回答2:

a++ is equivalent to a.operator++(0);. Your code is valid

13.5/7

When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.



回答3:

Yes, it is valid the int as a parameter it only a policy enforcing parameter to distinguish between prefix and postfix operators. The passed parameter will be received as an argument, which is the behavior you see & it is prfectly defined behavior.