Tuesday, February 23, 2016

[C++] friend

Encapsulation is a principle of OOP -> private member not accessible to outer class.

But, some times, we need to access in some situation.

friend reduce the time for type casting and safety check, but destroy the encapsulation.

1 friend class :  class A can access the private members of class B
2 friend method : method can access the private members of the class

Relation friend cannot be inherited
Relation friend is single directed A->B cannot have B->A
Relation friend is not transitif : A->B B->C  cannot have A-> C
Friend method is not a class member method, it's declared in the class, but for definition, we cannot write class::function_name for the method.


      class Point
 4   {
 5   public:
 6     Point(double xx, double yy) { x=xx; y=yy; }//默认构造函数
 7     void Getxy();//公有成员函数
 8     friend double Distance(Point &a, Point &b);//友元函数
 9   private:
10     double x, y;
11   };
12 
13   void Point::Getxy()
14   {
15        cout<<"("<
16   }
17 
18   double Distance(Point &a, Point &b)  //注意函数名前未加类声明符
19   {
20       double dx = a.x - b.x;
21       double dy = a.y - b.y;
22       return sqrt(dx*dx+dy*dy);
23   }
24 
25   void main()
26   {
27        Point p1(3.0, 4.0), p2(6.0, 8.0);
28        p1.Getxy();
29        p2.Getxy();
30        double d = Distance(p1, p2);
31        cout<<"Distance is"<
32   } 
 
 
For me, it's better to use setter and getter but not friend !

No comments:

Post a Comment