鱼C论坛

 找回密码
 立即注册
查看: 803|回复: 1

[已解决]后置运算符重载问题

[复制链接]
匿名鱼油
匿名鱼油  发表于 2022-1-18 15:39:38 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#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;
        return  cout;
}



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 就都可以了
回复

使用道具 举报

发表于 2022-1-18 15:45:40 | 显示全部楼层    本楼为最佳答案   
L l 这样会复制一份 l,然后传递给 operator<<
L &l 这样是引用已经存在的对象
后++ 得到的是一个 rvalue
L &l 需要一个 lvalue
const L &l 这样 lvalue 和 rvalue 就都可以了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-7-4 01:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表