成員函式過載運算子和友元函式過載運算子的比較
阿新 • • 發佈:2019-01-10
下面的例子可以很好的說明定義為friend function的好處.
#include <iostream.h>
class point
{
int x;
int y;
public:
point(int vx=0){x=vx;y=0;}
point(int vx,int vy):x(vx),y(vy){}
friend point operator +(point p1,point p2);
friend ostream & operator <<(ostream &output,point &p1);
};
point operator +(point p1,point p2)
{
point p;
p.x=p1.x+p2.x;
p.y=p1.y+p2.y;
return p;
}
#include <iostream.h>
class point
{
int x;
int y;
public:
point(int vx=0){x=vx;y=0;}
point(int vx,int vy):x(vx),y(vy){}
friend point operator +(point p1,point p2);
friend ostream & operator <<(ostream &output,point &p1);
};
point operator +(point p1,point p2)
{
point p;
p.x=p1.x+p2.x;
p.y=p1.y+p2.y;
return p;
}