c++之友元

友元是对类的辅助操作,他能够引用类中被隐藏的信息,使用友元的目的是基于对程序的运行效率,但也带来了一定的安全问题,友元可以是函数也可以是类,友元的关系式非传递的及X是Y的友元,Z是X的友元,但Z不一定是Y的友元

友元函数:

 1 #include<iostream>
 2 using namespace std ;
 3 #include<math.h>
 4 
 5 //用过友元函数计算两点之间的距离
 6 class Point
 7 { public:
 8       Point(double xi, double yi){
 9           X = xi ;
10           Y = yi ;
11       }
12       double GetX(){
13           return X ;
14       }
15       double GetY(){
16           return Y ;
17       }
18       //声明友元函数
19       friend double Distance ( Point & a, Point & b ) ;
20  private:  
21      double X, Y ;
22 } ;
23 //定义Distance函数
24 double Distance(Point & a, Point & b ){
25     //通过对象参数,访问私有成员
26     double dx = a.X - b.X ;
27     double dy = a.Y - b.Y ;
28     return sqrt ( dx * dx + dy * dy ) ;
29   }
30 int main(){
31     Point  p1( 3.0, 5.0 ) ,p2( 4.0, 6.0 ) ;
32     double  d = Distance ( p1, p2 ) ;
33     cout << "This distance is " << d << endl ;
34 } 

友元类:

若F类是A类的友元类,则F类的所有成员函数都是A类的友元函数

友元类通常设计为一种对数据操作或类之间传递消息的辅助类

 1 #include <iostream>
 2 using namespace std;
 3 class A{
 4     //类B是类A的友元
 5     friend class B;
 6 public:
 7     void disPlay(){
 8         cout << x << endl;
 9     }
10 private:
11     int x;
12 };
13 class B{
14 public:
15     void set(int i){
16         ab.x = i;
17     }
18     //通过类成员访问A类的私有数据
19     void disPlay(){
20         ab.disPlay();
21     }
22 private:
23     //类B的A类数据成员
24     A ab;
25 };
26 void main(){
27     B b;
28     b.set(100);
29     b.disPlay();
30 
31 }

 

posted @ 2015-03-08 01:50  溈鉨wo乄菰単  阅读(98)  评论(0编辑  收藏  举报