C++Note 运算符重载 加号 operator+
运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
加号运算符重载
作用:实现两个自定义数据相加的运算
PersonAddPerson可能会有多个名称 编译器提供通用名称:operator+
1 #include <iostream> 2 using namespace std; 3 //加号运算符重载 4 class Person 5 { 6 public: 7 //1.成员函数重载 + 号 8 //Person operator+(Person& p) 9 //{ 10 // Person temp; 11 // temp.m_A = this->m_A + p.m_A; 12 // temp.m_B = this->m_B + p.m_B; 13 // return temp; 14 //} 15 int m_A; 16 int m_B; 17 }; 18 //2.全局函数重载 + 号 19 Person operator+(Person& p1, Person& p2) 20 { 21 Person temp; 22 temp.m_A = p1.m_A + p2.m_A; 23 temp.m_B = p1.m_B + p2.m_B; 24 return temp; 25 } 26 //函数重载的版本 27 Person operator+(Person& p1, int num) 28 { 29 Person temp; 30 temp.m_A = p1.m_A + num; 31 temp.m_B = p1.m_B + num; 32 return temp; 33 } 34 void test() 35 { 36 Person p1; 37 p1.m_A = 10; 38 p1.m_B = 10; 39 Person p2; 40 p2.m_A = 10; 41 p2.m_B = 10; 42 Person p3 = p1 + p2; 43 //成员函数本质调用 Person p3 = p1.operator+(p2); 44 //全局函数本质调用 Person p3 = operaotr+(p1,p2); 45 cout << p3.m_A <<"\n" << p3.m_B << endl; 46 //运算符重载 也可以发生函数重载 47 Person p4 = p1 + 12;//Person + int 48 cout << p4.m_A << "\n" << p4.m_B << endl; 49 } 50 int main() 51 { 52 test(); 53 system("pause"); 54 return 0; 55 }
总结:
对于内置的数据类型的表达式的运算符是不可能改变的 例如 1+1不能等于3 只能等于2
不可以滥用运算符重载 例如 使用 operator+ 在内部实现实现减法或者除法等
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)