qq_40357294
Carlos134
采纳率100%
2020-04-16 13:54

为什么重载后置递增运算符用左移运算符重载输出时左移运算符重载函数形参不能用引用?

已采纳
#include <iostream>
#include <string>
using namespace std;
class person
{
    friend ostream& operator<<(ostream &cout,person p);
    private:
    int m_a;
    int m_b;
    public:
    person(int a,int b)
    {
        m_a=a;
        m_b=b;
    }
    //重载后置++运算符
        person operator++(int)  
    {
        person temp=*this;
        m_a++;
        m_b++;
        return temp;
    }
};
//全局函数重载左移运算符
ostream& operator<<(ostream &out,person p)    //???不能用引用&p
{
    out<<"m_a="<<p.m_a<<"   m_b="<<p.m_b;
    return out; 
}

void test()
{
    person pp(0,0);
    cout<<pp<<endl;
    cout<<pp++<<endl;
}

int main()
{
    test();
    system ("pause");
    return 0;
}

如果在全局函数重载那儿加了引用,即:

friend ostream& operator<<(ostream &cout,person &p);

ostream& operator<<(ostream &out,person &p)   

会报错,如下:
{

"owner": "C/C++",
"severity": 8,
"message": "没有与这些操作数匹配的 \"<<\" 运算符 -- 操作数类型为:  std::ostream << person",
"startLineNumber": 36,
"startColumn": 9,
"endLineNumber": 36,
"endColumn": 9

}
但是不加引用可以正常运行。为什么????

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答