Anonymous 发表于 2022-1-18 15:39:38

后置运算符重载问题

#include<iostream>
using namespace std;
class L
{
        friend ostream& operator<<(ostream& cout, L l);

public:
        L()
        {
                m_A = 0;
                m_B = 0;
        }

        L& operator++()
        {
                ++m_A;
                ++m_B;
                return*this;

        }

        L operator++(int)
        {
                L temp = *this;
                m_A++;
                m_B++;
       
                return temp;

        }



private:


        int m_A ;
        int m_B;

};


ostream& operator<<(ostream &cout,L l)
{
        cout << l.m_A << endl;
        cout << l.m_B << endl;
        returncout;
}



void test01()
{
        L l;

        cout << ++l << endl;


}

void test02()

{
        L l;
        cout << l++ << endl;

}



int main()
{
        test01();
        test02();


        system("pause");
        return 0;
}

代码ostream& operator<<(ostream &cout,L l)改成引用 ostream& operator<<(ostream &cout,L&l)以后,调用后置运算符重载的函数就会报错,不知道是怎么回事,求懂的大佬解答一下

人造人 发表于 2022-1-18 15:45:40

L l 这样会复制一份 l,然后传递给 operator<<
L &l 这样是引用已经存在的对象
后++ 得到的是一个 rvalue
L &l 需要一个 lvalue
const L &l 这样 lvalue 和 rvalue 就都可以了
页: [1]
查看完整版本: 后置运算符重载问题