友员用关键字friend声明。
友员是对类操作的一种辅助手段。
一个类的友员可以访问该类各种性质的成员。
一、友元函数
1、友员函数通过对象参数访问私有数据成员2、成员函数通过this指针在对象上操作
友元函数 VS 成员函数:
lass A
{ private:
int i ;
friend void FriendFun(A * , int) ;
public:
void MemberFun(int) ;
} ;
void FriendFun( A * ptr , int x )
{
ptr -> i = x ;
}
void A:: MemberFun( int x )
{
i = x ;
}
void Test()
{
FriendFun( &Aobj, 5 ) ;
Aobj.MemberFun( 5 ) ;
}
用友员函数计算两点之间的距离 :
class Point
{ public:
Point(double xi, double yi) { X = xi ; Y = yi ;}
double GetX() { return X ; }
double GetY() { return Y ; }
friend double Distance ( Point & a, Point & b ) ;
private: double X, Y ;
} ;
double Distance(Point & a, Point & b )
{ double dx = a.X - b.X ;
double dy = a.Y - b.Y ;
return sqrt ( dx * dx + dy * dy ) ;
}
void main()
{ Point p1( 3.0, 5.0 ) , p2( 4.0, 6.0 ) ;
double d = Distance ( p1, p2 ) ;
cout << "This distance is " << d << endl ;
}
二、友员类
1、若F类是A类的友员类,则F类的所有成员函数都是A类的友员函数
2、友员类通常设计为一种对数据操作或类之间传递消息的辅助类
class A
{
friend class B ;//类 B 是类 A 的友员
public :
void Display() { cout << x << endl ; } ;
private :
int x ;
} ;
//B类没有数据成员仅提供对A类的操作
class B
{ public :
void Set ( int i ) { Aobject . x = i ; } //通过类成员访问A类的私有数据成员
void Display () { Aobject . Display () ; } //通过类成员调用A类的成员函数
//通过对象参数访问友员的成员
void Set (A & Aobject , int i) { Aobject . x = i ; }
void Display (A & Aobject ) { Aobject . Display() ; }
private :
A Aobject ; //类 B 的 A 类数据成员
} ;
void main()
{ B Bobject ;
Bobject.Set ( 100 ) ;
Bobject.Display () ;
}