Return value of operator++

This question already has an answer here:

  • What are the basic rules and idioms for operator overloading? 7 answers

  • You attempt to apply the second ++ to the temporary object returned by the first invocation. However, the operand must be passed by reference, and you can't bind a temporary to a non-constant lvalue reference.

    You probably don't want to "fix" this, since there's little reason to modify a temporary value like that. However, you should return a copy of the value before incrementing it, to give the expected post-increment behaviour.

    The prefix operator should return a reference, which can be happily bound to another reference so that ++++x; should work as expected.


    You are incrementing the return value of the inner operator++ by writing x++ ++ . That means that the code won't compile if the return value of that operator is not something that can be modified.

    So if you declare it to return Number instead of Number & , then it can't be modified (the return value of a function is a temporary and not an lvalue unless it's a reference, hence the outer operator++, which takes it by (non-const) reference, can't bind it to an object returned by value).


    What you are trying to do is very unusual. Post-increment usually returns an rvalue representing the object before the increment (as opposed to pre-increment, which first increments the object and then returns that object itself, as an lvalue). You are basically trying to make post-increment behave the same way as pre-increment, for inexplicable reasons.

    Normally, you would do something like this:

    class Number {
      int n;
    public:
      // Pre-increment
      Number& operator++() {
        ++n;
        return *this;
      }
      Number operator++(int) {
        Number temp = *this;  // capture old value
        ++(*this);
        return temp;
      }
    };
    

    With this definition, x++++ doesn't compile - but it also doesn't compile when x is an int : it doesn't really make much sense.

    Anyway, the reason it doesn't work for you is as follows. x++++ is interpreted as

    operator++(operator++(x, 0), 0)
    

    The inner operator++ call returns a temporary Number object. The outer operator++() expects a parameter of type Number& - but a non-const reference can't bind to a temporary. When you change the declaration so that operator++ returns Number& - an lvalue - then this return value can be happily passed to the outer operator++ call.

    链接地址: http://www.djcxy.com/p/12696.html

    上一篇: 用于std :: cout的运算符<< C ++链接

    下一篇: 运算符++的返回值