版权声明: https://blog.csdn.net/qq_40794602/article/details/85220682
利用成员函数进行重载:
#include<iostream> using namespace std; class Test { public: Test(){} Test(int t) { m_a = t; } Test operator+(Test oth) //方法1:利用成员函数进行加好运算符重载 { Test tem; tem.m_a = this->m_a + oth.m_a; return tem; } int m_a; }; int main() { Test t1(1); Test t2(2); Test t3 = t1 + t2; cout << "t3.m_a:" << t3.m_a << endl; return 0; }
利用全局函数进行重载:
#include<iostream> using namespace std; class Test { public: Test(){} Test(int t) { m_a = t; } int m_a; }; Test operator+(Test t1, Test t2) //利用全局函数进行加号运算符重载 { Test t3; t3.m_a = t1.m_a + t2.m_a; return t3; } int main() { Test t1(1); Test t2(2); Test t3 = t1 + t2; cout << "t3.m_a:" << t3.m_a << endl; return 0; }
重载运算符函数可以有多个版本,可以自己写不同的重载,根据参数类型进行区分