//运算符重载之链式编程
#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");
}