1.普通的非成员函数友元
#include "cmath"
#include "iostream"
using namespace std;
class Point
{
public:
Point(double xx,double yy)
{
x=xx;
y=yy;
}
void GetXY();
friend double Distance(Point &a,Point &b);
protected:
private:
double x,y;
};
void Point::GetXY()
{
//cout<<"("<<this->x<<","<<this->y<<")"<<endl;
cout<<"("<<x<<","<<y<<")"<<endl;
}
double Distance(Point &a,Point &b)
{
double length;
length=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); //它可以引用类中的私有成员
return length;
}
int main(void)
{
Point p1(3.0,4.0),p2(6.0,8.0);
p1.GetXY(); //成员函数的调用方法,通过使用对象来调用
p2.GetXY();
double d = Distance(p1,p2); //友元函数的调用方法,同普通函数的调用一样,不要像成员函数那样调用
cout<<d<<endl;
system("pause");
return 0;
}
说明:在该程序中的Point类中说明了一个友元函数Distance(),它在说明时前边加friend关键字,标识它不是成员函数,而是友元函数。它的定义方法与普通函数定义一样,而不同于成员函数的定义,因为它不需要指出所属的类。但是,它可以引用类中的私有成员,函数体中的a.x,b.x,a.y,b.y都是类的私有成员,它们是通过对象引用的。在调用友元函数时,也是同普通函数的调用一样,不要像成员函数那样调用。本例中,p1.Getxy()和p2.Getxy()这是成员函数的调用,要用对象来表示。而Distance(p1, p2)是友元函数的调用,它直接调用,不需要对象表示,它的参数是对象。(该程序的功能是已知两点坐标,求出两点的距离。)
下面对上面的代码进行输入、输出流的重载:
#include <cmath>
#include <iostream>
using namespace std;
class Point
{
public:
Point(double xx,double yy)
{
x=xx;
y=yy;
}
void GetXY();
friend double Distance(Point &a,Point &b);
friend ostream &operator <<(ostream &a,Point &b);
protected:
private:
double x,y;
};
// friend ostream& operator<<(ostream& o,A& another);
ostream &operator <<(ostream &out,Point &b) //在类中声明的时候,可以是ostream &a,函数定义的时候也可以是ostream &out
{
out<<"("<<b.x<<","<<b.y<<")"<<endl;
return out;
}
void Point::GetXY()
{
//cout<<"("<<this->x<<","<<this->y<<")"<<endl;
//cout<<"("<<x<<","<<y<<")"<<endl;
cout<<*this;
}
double Distance(Point &a,Point &b)
{
double length;
length=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
return length;
}
int main(void)
{
Point p1(3.0,4.0),p2(6.0,8.0);
p1.GetXY();
p2.GetXY();
double d = Distance(p1,p2);
cout<<d<<endl;
system("pause");
return 0;
}










