C++ 运算符重载三(链式编程)

//运算符重载之链式编程
#include<iostream>
using namespace std;

//对于友元函数重载运算符只适用于左操作数是系统变量的场景
//因为成员无法在系统变量中添加类成员函数,只能靠全局函数来实现
//链式编程的本质是:函数返回值当左值
class Point { public: //注意友元函数中,返回值不同,友元函数就会不同,跟函数重载有区别 friend ostream & operator<<(ostream &out, Point& pin); Point(int x,int y){ this->x = x; this->y = y; } Point(Point &p){ this->x = p.x; this->y = p.y; cout << "拷贝构造函数被执行了1" << endl; } ~Point(){ cout << "析构函数被执行了2" << endl; } void PrintfA(){ cout << "x=" << this->x << endl; cout << "y=" << this->y << endl; } private: int x; int y; }; //第一个版本(非链式编程) /* void operator<<(ostream &out, Point& pin){ out << "x=" << pin.x << endl; out << "y=" << pin.y << endl; } */ //第二个版本(链式编程) ostream & operator<<(ostream &out, Point& pin){ out << "x=" << pin.x << endl; out << "y=" << pin.y << endl; return out; } void ProtectA(){ Point p1(5, 5); //需求:我们需要打印这个类对象,而系统无法打印自定义的类,那么我们必须重载<<运算符 //对于二元运算符,补充一点,两个操作数的位置也很关键 //例如:cout << p1,左操作数是cout,右操作数是p1,如果写成类成员函数 那么必须 cout.operator<<(p1) //这里我们显然无法在cout这个对象对应的类中添加运算符重载,只能使用友元函数 cout << p1; //步骤1:首先承认运算符重载是一个函数,写出函数名 //operator<<() //步骤2:根据操作数,写出参数列表 //operator<<(cout,p1) //步骤3:根据业务完成函数返回值,以及实现函数 //void operator<<(cout,p1) cout的类型是 ostream //现在开始引入链式编程 //对于 cout << p1<<"asdfasdfas"<<endl; //cout << p1 << "asdfasdfas" << endl; 报错 error C2296: “<<”: 非法,左操作数包含“void”类型 //意思是 void类型没有重载运算符<<,而实际上cout << p1函数应该返回cout变量,那么就可以实现输出"asdfasdfas" //因此修改产生版本二 cout << p1 << "asdfasdfas" << endl; } void main(){ ProtectA(); system("pause"); }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值