C++ 操作符重载
1、为什么要使用操作符重载?
操作符和方法在本质上一样,使用操作符更符合人性化的描述。
2、操作符重载分为 普通操作符重载和成员操作符重载,区别在于:
a、普通操作符重载要访问对象的私有成员,因此要设计为friend,而成员操作符重载不需要;
b、相比于普通操作符重载,成员操作符重载,少了一个形参,因为成员方法总是与对象绑定使用的,被绑定的对象就是操作符的第一个参数;
示例代码:

1 #include "StdAfx.h" 2 3 class Point 4 { 5 private : 6 int x; 7 int y; 8 9 public : 10 Point (); 11 12 Point(int x,int y); 13 14 void Print()const; 15 16 void Set(int x,int y); 17 18 friend Point operator+(const Point& a, const Point& b); 19 20 friend Point operator+(const Point& a, int b); 21 22 Point operator-(const Point& b) 23 { 24 Point s; 25 s.Set(this->x-b.x, this->y-b.y); 26 return s; 27 } 28 29 Point operator-(int b) 30 { 31 Point s; 32 s.Set(this->x-b, this->y-b); 33 return s; 34 } 35 };

1 #include "StdAfx.h" 2 #include <iostream> 3 #include "Point.h" 4 5 Point ::Point() 6 { 7 } 8 9 Point::Point(int x,int y) 10 { 11 this->x = x; 12 this->y = y; 13 } 14 15 void Point::Print()const 16 { 17 std::cout<<"X:"<<x<<" Y:"<<y<<std::endl; 18 } 19 20 Point operator+(const Point& a,const Point& b) 21 { 22 Point s(a.x+b.x,a.y+b.y); 23 24 return s; 25 } 26 27 28 Point operator+(const Point& a,int b) 29 { 30 Point s(a.x+b,a.y+b); 31 32 return s; 33 } 34 35 void Point::Set(int x,int y) 36 { 37 this->x = x; 38 this->y = y; 39 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理