11.5.2重学C++之【左移运算符重载】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;


/*
    4.5.2 左移运算符重载
        可以输出自定义的数据类型
*/


class Person{
public:
    int a;
    int b;

    // 尝试利用成员函数重载左移运算符 p.operator<<(cout) 简化为 p << cout
    // 不会利用成员函数重载<<运算符,因为无法实现cout在左侧
    // 成员函数 实现不了  p << cout 不是我们想要的效果
    /*
    void operator<<(Person & p){ // (cout)

    }
    */
};


// 只能利用全局函数重载左移运算符
/*
void operator<<(ostream & cout, Person & p){ // 本质:operator<<(cout, p) 简化为 cout << p
    cout << "a=" << p.a << ",b=" << p.b << endl;
}
*/

//ostream对象全局只能有一个
ostream & operator<<(ostream & cout, Person & p){ // 本质:operator<<(cout, p) 简化为 cout << p
    cout << "a=" << p.a << ",b=" << p.b;
    return cout;
}
// 本函数的cout可以改为out等其他名称,实质为起别名




void test1(){
    Person p;
    p.a = 10;
    p.b = 10;
    cout << p.a << endl;
    cout << p.b << endl;

    //cout << p; // 正常本行报错;重载<<后可以实现
    cout << p << ",hello" << endl; // 链式编程思想
}


int main()
{
    test1();

    system("pause");
    return 0;
}

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;



class Person{

    friend ostream & operator<<(ostream & out, Person & p);

private:
    int a;
    int b;

public:
    /*
    Person(int _a, int _b){
        a = _a;
        b = _b;
    }
    */
    Person(int a, int b){ // 该函数效果实质同上
        this->a = a;
        this->b = b;
    }
};



//ostream对象全局只能有一个
ostream & operator<<(ostream & out, Person & p){
    out << "a=" << p.a << ",b=" << p.b;
    return out;
}




void test1(){
    Person p(10, 10);

    cout << p << ",hello" << endl; // 链式编程思想
}




int main()
{
    test1();

    system("pause");
    return 0;
}
posted @   yub4by  阅读(35)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示