运算符重载双做尖括号

运算符重载

在这里插入图片描述

人在世上练,刀在石上磨

1、重载运算符的概述

运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
运算符重载的目的:简化操作 让已有的运算符 适应适应不同的数据类型。
语法:函数的名字由关键字operator及其紧跟的运算符组成
比如:重载+运算符 == > operator+ 重载=号运算 ==>operator=
注意:重载运算符 不要更改 运算符的本质操作(+是数据的相加 不要重载成相减)

2、运算符<<的重载

#include <iostream>
#include<string.h>
using namespace std;
class Person
{
private:
    char *name;
    int num;
public:
    Person(char *name, int num)
    {
        this->name = new char[strlen(name)+1];
        strcpy(this->name,name);
        this->num = num;
        cout<<"有参构造"<<endl;
    }
    //普通的成员函数
    void printPerson(void)
    {
        cout<<"name = "<<name<<", num = "<<num<<endl;
    }
    ~Person()
    {
        if(this->name != NULL)
        {
            delete [] this->name;
            this->name = NULL;
        }
        cout<<"析构函数"<<endl;
    }
};
int main(int argc, char *argv[])
{
    Person ob1("lucy",18);
    //普通的成员函数 遍历信息
    //ob1.printPerson();

    //cout默认输出方式 无法识别 自定义对象 输出格式
    //cout<<ob1<<endl;//err
    return 0;
}

截图:
在这里插入图片描述
解决上述问题 需要重载<<
在这里插入图片描述
解决办法:将operator<<设置成友元:

完整代码:

#include <iostream>
#include<string.h>
using namespace std;
class Person
{
    //设置成友元函数 在函数内 访问Person类中的所有数据
    friend ostream& operator<<(ostream &out, Person &ob);
private:
    char *name;
    int num;
public:
    Person(char *name, int num)
    {
        this->name = new char[strlen(name)+1];
        strcpy(this->name,name);
        this->num = num;
        cout<<"有参构造"<<endl;
    }
    //普通的成员函数
    void printPerson(void)
    {
        cout<<"name = "<<name<<", num = "<<num<<endl;
    }
    ~Person()
    {
        if(this->name != NULL)
        {
            delete [] this->name;
            this->name = NULL;
        }
        cout<<"析构函数"<<endl;
    }
};

ostream& operator<<(ostream &out, Person &ob)//out=cout, ob =ob1
{
    //重新实现 输出格式
    out<<ob.name<<", "<<ob.num;

    //每次执行为 返回值得到cout
    return out;
}
int main(int argc, char *argv[])
{
    Person ob1("lucy",18);
    //普通的成员函数 遍历信息
    //ob1.printPerson();

    //cout默认输出方式 无法识别 自定义对象 输出格式
    //cout<<ob1<<endl;//err

    //运算符重载的调用方式1:
    operator<<(cout, ob1)<<endl;
    //运算符重载的调用方式2:
    //对方法1 进行优化 去掉operator,第一个参数 放在运算符<<的左边  第二个参数 放在运算符<<的右边
    cout<<ob1<<endl;//等价operator<<(cout, ob1);

    Person ob2("bob",19);
    cout<<ob1<<" "<<ob2<<endl;

    return 0;
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值