C++ 运算符重载一(二元运算符重载)
//二元运算符重载 #include<iostream> using namespace std; class Point { public: Point(int x,int y){ this->x = x; this->y = y; } //为什么要使用友元函数呢 friend Point operator+(Point &p1, Point &p2); //类成员函数实现二元运算符- Point operator-(Point &pin){ //二元运算符最好不要改变原来的变量 Point temp = *this; temp.x = this->x - pin.x; temp.y = this->y - pin.y; return temp; } void PrintfA(){ cout << "x=" << this->x << endl; cout << "y=" << this->y << endl; } private: int x; int y; }; //友元函数 //因为函数中使用类的私有成员属性 Point operator+(Point &p1, Point &p2){ Point pres(p1.x+p2.x,p1.y+p2.y); return pres; } void ProtectA(){ //重载二元运算符 + Point p1(1, 1), p2(2, 2); Point p3 = p1 + p2; //全局函数(一般是友元函数),类成员函数实现运算符重载步骤 //步骤1:要承认操作符重载是一个函数,写出函数名称 //operator+ //步骤2:根据操作数,写出函数参数列表 //operator+(p1, p2); //步骤3:根据业务,完成函数返回值,及实现函数 //p3=operator + (p1, p2); p3.PrintfA(); //用类成员们函数实现 //由全局函数变成类成员函数 Point p4 = p1 - p2; //步骤1:要承认操作符重载是一个函数,写出函数名称 //operator-() //步骤2:根据操作数,写出函数参数列表, ///在类中,对象本身是this,所有可以少传递一个变量 //p1.operator-(p2); //步骤3:根据业务,完成函数返回值,及实现函数 p4.PrintfA(); } void main(){ ProtectA(); system("pause"); }