友元函数和友元类
友元的对象可以是全局的一般函数,也可以是其它类里的成员函数,这种叫做友元函数。
友元还可以是一个类,这种叫做友元类,这时整个类的所有成员都是友元

一、友元函数
- 类的友元函数定义在类的外部,但是有权访问类的所有私有成员和保护成员。但友元函数并不是成员函数。
 
- 有元函数的声明使用
friend关键字 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
   | #include<iostream> #include<math.h> using namespace std;
  class Point { 	private: 		double x; 		double y; 	public: 		Point(double a,double b)     		{ 			x=a; 			y=b; 		} 		int GetPoint() 		{ 			cout<<"("<<x<<","<<y<<")"<<endl; 			return 0; 		} 		friend double Distance(Point &a,Point &b); };
  double Distance(Point &a,Point&b) { 	double xx; 	double yy; 	xx = a.x-b.x; 	yy = a.y-b.y; 	return sqrt(xx*xx+yy*yy); }
  int main() { 	Point A(2.0,3.0); 	Point B(1.0,2.0); 	A.GetPoint(); 	B.GetPoint(); 	double dis; 	dis = Distance(A,B); 	cout<<dis<<endl; 	return 0; }
   | 
 

友元函数没有this指针,参数的情况;
- 要访问非static成员时,需要对象做参数
 
- 要访问static成员或全局变量时,则不需要对象做参数
 
- 如果做参数的对象时全局对象,则不需要对象做参数,可直接调用友元函数,不需要通过对象或指针。
 
二、友元类
把一个类A声明为另一个类B的友元类,则类A中的所有成员函数都可以访问类B中的成员。在类B中声明即可。
friend class A;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
   | #include<iostream> #include<Cmath> using namespace std;
  class Point { 	private: 	    double x; 		double y; 	public: 	    Point(double a,double b) 		{ 			x=a; 			y=b; 		} 		int GetPoint() 		{ 			cout<<"("<<x<<","<<y<<")"<<endl; 			return 0; 		} 	friend class Tool; };
  class Tool {     public: 	    double Get_x(Point &A ) 		{ 			return A.x; 		} 	    double Get_y(Point &A) 	    { 	    	return A.y; 		} 		double Distance(Point &A)   		{ 			cout<<sqrt(A.x*A.x+A.y*A.y)<<endl; 			return sqrt(A.x*A.x+A.y*A.y); 		} } ;
  int main() { 	Point A(3.0,3.0); 	A.GetPoint(); 	Tool T; 	T.Get_x(A); 	T.Get_y(A); 	T.Distance(A); 	return 0; }
   | 
 
