30.左移运算符重载

1.视频内容

程序1:

#pragma warning(disable:4996)
//2022年10月5日21:11:12
#include <iostream>
using namespace std;

class Maker
{
public:
    Maker(int id, string name)
    {
        this->id = id;
        this->name = name;
    }
public:
    int id;
    string name;
};

//1.形参和实参是一个对象
//2.不能改变库中的代码
//3.ostream中把拷贝构造私有化了
void operator<<(ostream &out, Maker &m)
{
    cout << m.id << " " << m.name << endl;
}

void test01()
{
    Maker m(10, "小花");
    cout << m;
}

int main()
{
    test01();
    system("pause");
    return EXIT_SUCCESS;
}

输出结果:

10 小花
请按任意键继续. . .


程序2:

#pragma warning(disable:4996)
//2022年10月5日21:11:12
#include <iostream>
using namespace std;

class Maker
{
public:
    Maker(int id, string name)
    {
        this->id = id;
        this->name = name;
    }
public:
    int id;
    string name;
};

//1.形参和实参是一个对象
//2.不能改变库中的代码
//3.ostream中把拷贝构造私有化了
//4.如果要和endl一起使用,那么必须返回ostream的对象
ostream &operator<<(ostream &out, Maker &m)
{
    cout << m.id << " " << m.name << endl;

    return out;
}

void test01()
{
    Maker m(10, "小花");
    cout << m;
    cout << endl;

    cout << 10;//内部重载了数据类型
}

int main()
{
    test01();
    system("pause");
    return EXIT_SUCCESS;
}

输出结果:

10 小花

10请按任意键继续. . .

2.左移和右移运算符重载(重点难点)

1.左移运算符重载

​ A.cout是对象,<<是左移运算符

​ B.重载左移运算符是为了直接打印对象

​ C.形参和实参是一个对象

​ D.不能改变库类中的代码

​ E.ostream中把拷贝构造函数私有化了

​ F.如果要和endl一起使用,那么必须返回ostream的对象.

posted @   CodeMagicianT  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示