coffee++ 2025-03-04 13:08 采纳率: 100%
浏览 2
已结题

重载<<运算符时endl是怎样的?

重载<<运算符时endl是怎样的?

//给出如下定义的重载函数
ostream& operator << (ostream &cout, Person p) {
    cout << "a = " << p.a << endl << "b = " << p.b << endl;
    return cout;
}
//当我输出Person类型时
cout<<p<<p<<p<<endl;//这样是可行的

cout<<p;
//等价于
operator<<(cout,p);

cout<<p<<p;
//等价于
operator<<(operator(cout,p),p);

//那请问下面的代码等价于什么?
cout<<p<<endl;
//如果说是operator<<(operator(cout,p),endl);
//显然是错误的,因为endl不是Person类型
  • 写回答

3条回答 默认 最新

  • 码农阿豪@新空间 新星创作者: 前端开发技术领域 2025-03-04 13:31
    关注
    让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
    当执行 `cout << p << endl;` 时,这条语句等价于 `cout << p` 调用了重载的输出运算符,然后再将 `endl` 插入到输出流中,实现换行的效果。因此,该语句等价于 `operator<<(cout, p) << endl;`。 以下是完整的代码示例:
    #include <iostream>
    using namespace std;
    class Person {
    public:
        int a;
        int b;
        Person(int a, int b) : a(a), b(b) {}
    };
    ostream& operator<<(ostream& cout, Person p) {
        cout << "a = " << p.a << endl
             << "b = " << p.b << endl;
        return cout;
    }
    int main() {
        Person p(10, 20);
        
        cout << p << endl;
        return 0;
    }
    

    运行以上代码,输出结果为:

    a = 10
    b = 20
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月12日
  • 已采纳回答 3月4日
  • 创建了问题 3月4日