1

`

#include<iostream>
using namespace std;
class MyInteger {

    friend ostream& operator<<(ostream& out, MyInteger& myint);

public:
    MyInteger() {
        m_Num = 0;
    }
    //Front++
    MyInteger& operator++() {
        m_Num++;
        return *this;
    }

    //Rear ++
    MyInteger operator++(int) {
        MyInteger temp = *this; 
        m_Num++;
        return temp;
    }

private:
    int m_Num;
};


ostream& operator<<(ostream& out, MyInteger& myint) {
    out << myint.m_Num;
    return out;
}


void test01() {
    MyInteger myInt;
    cout << ++myInt << endl;
    cout << myInt << endl;
}

void test02() {

    MyInteger myInt;
    cout << myInt++ << endl;
    cout << myInt << endl;
}

int main() {

    test01();
    //test02();

    system("pause");

    return 0;
}

` When I reload cout, the alias of MyInteger is passed in. Why can't I output the ++ postposition that I overloaded at this time. The hint is that there is no "<<" operator that matches these operands.But when I do not pass in the alias, it can be output normally.I want to know what caused it.

David
  • 11
  • 2
  • 2
    Change `MyInteger& myint` to `const MyInteger& myint` – UnholySheep Nov 24 '20 at 15:55
  • Does this answer your question? [Why not non-const reference to temporary objects?](https://stackoverflow.com/questions/13826897/why-not-non-const-reference-to-temporary-objects) – UnholySheep Nov 24 '20 at 15:56

1 Answers1

2

Your post-increment will return by value

MyInteger operator++(int) {
    MyInteger temp = *this; 
    m_Num++;
    return temp;
}

Therefore myInt++ will return a temporary, and you cannot bind a temporary to a non-const reference

ostream& operator<<(ostream& out, MyInteger& myint)

You can, however, use a const reference to extend the lifetime of the temporary

ostream& operator<<(ostream& out, MyInteger const& myint)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    Nitpicking. As a temporary argument passed to a const-reference parameter, the const reference does not *extend the lifetime of the temporary*. The temporary's lifetime is controlled at the callsite. – Eljay Nov 24 '20 at 16:05
  • After using const, the returned temporary variable becomes a constant reference, so it can be passed in normally. Is this understanding correct? – David Nov 25 '20 at 04:45
  • @David The returned temporary will live until the end of the full expression in which it was created. It doesn't become a reference per se, but the `MyInteger const&` `myint` will bind to the (unnamed) temporary returned by your operator. – Ted Lyngmo Nov 30 '20 at 20:16