方法一
在类声明里实现友元函数
#include<bits/stdc++.h>
using namespace std;
class point
{
private :
int a;
public:
point (int A=10)
{
a=A;
}
friend operator +(point A,point B)
{
cout<<A.a+B.a;
}
};
int main()
{
point obj1(1),obj2(5);
obj1+obj2;
return 0;
}
输出6
方法二
编写私有成员的外部接口
#include<bits/stdc++.h>
using namespace std;
class point
{
private :
int a;
public:
point (int A=10)
{
a=A;
}
int get_a(){return a;}; //私有成员a的外部接口
friend int operator+(point A,point B);
};
int operator+(point A,point B)
{
return A.get_a()+B.get_a();
}
int main()
{
point obj1(1),obj2(5);
cout<<obj1+obj2;
return 0;
}
输出 6
以上两种方法是比较方便和可行的,当然还有其他方法了,这里就暂时不讨论了。