010_linuxC++之_运算符重载
(一)运算符重载:运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
(二)实现类不同对象里中变量的相加
(三)程序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string.h> 3 #include <unistd.h> 4 5 using namespace std; 6 7 class Point { 8 private: 9 int x; 10 int y; 11 12 public: 13 Point() {} 14 Point(int x, int y) : x(x), y(y) {} 15 16 void printInfo() 17 { 18 cout<<"("<<x<<", "<<y<<")"<<endl; 19 } 20 friend Point operator+(Point &p1, Point &p2); 21 }; 22 23 24 Point operator+(Point &p1, Point &p2) 25 { 26 cout<<"Point operator+(Point &p1, Point &p2)"<<endl; 27 Point n; 28 n.x = p1.x+p2.x; 29 n.y = p1.y+p2.y; 30 return n; 31 } 32 33 34 int main(int argc, char **argv) 35 { 36 Point p1(1, 2); 37 Point p2(2, 3); 38 39 Point sum = p1+p2; 40 sum.printInfo(); 41 42 return 0; 43 }
(四)运行结果