注意:类内运算符重载时只能有且仅有一个参数;类内其他函数可以有多个参数。
如果参数过多:
方法一:利用全局函数类外实现;
方法二:利用友元类内实现
#include <iostream>
using namespace std;
#include <string>
class person
{
public:
person(int a, int b)
{
m_a = a;
m_b = b;
}
int m_a;
int m_b;
person &add_person(person& p)
{
this->m_a+=p.m_a ;
this->m_b += p.m_b;
return *this;
}
person operator+(person& p)
{
person temp(0,0);
temp.m_a = this->m_a + p.m_a;
temp.m_b = this->m_b + p.m_b;
return temp;
}
//方法二:利用友元类内实现
//friend ostream& operator<<(ostream& cout, person p);//本质:简化为cout<<p
};
//方法一:利用全局函数类外实现;
ostream& operator<<(ostream& cout, person p)//本质:简化为cout<<p
{
cout << "m_a=" << p.m_a << "\tm_b=" << p.m_b;
return cout;
}
int main()
{
person p1(1, 2);
person p2(1, 2);
person p = p1 + p2;
cout << p1<< endl;
system("pause");
return 0;
}