对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
作用:实现两个自定义数据类型相加的运算
1.加号运算符重载
#include<iostream> #include<string> using namespace std; class person { public: //成员函数实现 + 号运算符重载 person operator+(person&p) { person temp; temp.A=this->A+p.A; temp.B=this->B+p.B; return temp; } public: int A; int B; }; //全局函数实现 + 号运算符重载 Person operator+(const Person& p1, const Person& p2) { Person temp(0, 0); temp.m_A = p1.m_A + p2.m_A; temp.m_B = p1.m_B + p2.m_B; return temp; } void text() { person p1; p1.A=10; p1.B=10; person p2; p2.A=10; p2.B=10; person p3=p1+p2; cout<<"p3.A= "<<p3.A<<endl; cout<<"p3.B= "<<p3.B<<endl; } int main() { text(); }
2.
原文:https://www.cnblogs.com/hyt01/p/14250464.html