C++运算符重载

运算符重载基本概念

运算符重载(operator overloading)只是一种”语法上的方便”,也就是它只是另一种函数调用的方式。
运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。

案例: 重载左移操作符(<<),使得 cout 可以输出对象。

#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; //重新实现 输出格式
    return out; //每次执行为 返回值得到cout
}
int main(int argc, char *argv[])
{
    Person ob1("lucy",18);
    operator<<(cout, ob1)<<endl;
    // 进行优化 去掉operator,第一个参数 放在运算符<<的左边  第二个参数 放在运算符<<的右边
    cout<<ob1<<endl;//等价operator<<(cout, ob1);
    Person ob2("bob",19);
    cout<<ob1<<" "<<ob2<<endl;
    return 0;
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值