C + + 's friend mechanism (friend function and friend Class)

Source: Internet
Author: User
Tags define function gety

First, why the introduction of friend mechanism? In general, to let non-member functions, ordinary functions or other classes can access the private members of the class, which does undermine the encapsulation of the class and data concealment, but why do you want to do so? (C + + primer: Although a friend is granted permission to access the private part of a class from outside, it is not contrary to object-oriented programming ideas, but instead improves the flexibility of the public interface). To understand this, you must know the process of forming a friend: (any function, or member function, or class that wants to be a friend of a class, is determined by this class, and cannot be imposed externally)

We already know that classes have attributes for encapsulation and information hiding. Only member functions of a class can access private members of a class, and other functions in the program cannot access private members. Non-member functions can access public members in a class, but if the data members are defined as public, this destroys the hidden attributes. In addition, it should be seen that in some cases, especially when multiple calls are made to certain member functions, the time cost is required for parameter passing, type checking and security checking, which affects the efficiency of the program.

In order to solve the above problems, a scheme is proposed to make the UF element. A friend is a normal function that is defined outside the class, but it needs to be described in the class, and in order to distinguish it from the member functions of the class, the keyword friend is preceded by the description. A friend is not a member function, but it can access a private member in a class. The role of friends is to improve the operational efficiency of the program (that is, reducing the time overhead required for type checking and security checks, etc.), but it destroys the encapsulation and concealment of classes, allowing non-member functions to access private members of the class.

the form of the friend functionFriends are mainly divided into friend function and friend class, in the TV and Remote control example, TV and remote control can be controlled television (change, adjust volume, switch mode, etc.), but TV and remote control is not derived from the relationship, in order to reuse and control the TV, you can declare the remote control class as a friend of the TV class, So all the functions in the remote control class can use all the members of the TV class, including all the operations in the multiplex TV, but found that in addition to the channel of the TV's private members, the other private members in the TV's public interface can be accessed, then there is no need for the entire remote control class declared as Friend class, Just declare this function of the direct operation channel as the friend function of the TV.a "friend function" within a class can only declare function prototypes, cannot define function bodies, and is not a restriction of access levels. Each member of the friend class can access protected and private members in another class. NOTE: Calling a private member requires an object, namely: the object name. Variable. For a normal private member variable is accessed through an object, for a private static variable is accessed through the class

1. A simple introduction to the friend function

1.1 Why to make the UF meta-function

Reduce system overhead and increase efficiency when data sharing between classes is implemented. If a function in Class A accesses a member in Class B (for example, the implementation of a smart pointer Class), then the function in Class A is a friend function of Class B. Specifically, in order to enable member functions of other classes to access the private variables of the class directly. That is, allow the outside class or function to access the class's private and protection variables, so that two classes share the same function.

In fact, there are about two situations in which you need to use friend functions: (1) operator overloading for some situations where you need to use friends. (2) Two classes to share data.

1.2 Advantages and disadvantages of using friend functions

Advantages: Can improve efficiency, express simple, clear.

Disadvantage: The friend function breaks the encapsulation mechanism, tries not to use the member function, unless the unavoidable situation makes the UF meta-function.

2. Use of friend functions

2.1 Arguments to the friend function:

Because the friend function does not have this pointer, there are three conditions for the parameter:

(1) To access non-static members, the object is required to do the parameters;

(2) If you want to access static members or global variables, you do not need the object to do parameters;

(3) If the object that makes the parameter is the global object, then the object does not need to do the parameter;

2.2 The location of the friend function

Because a friend function is a function outside the class, its declaration can be placed in the private or public segment of the class without distinction.

2.3 Call of the friend function

You can directly adjust the cell function, do not need to pass through the object or pointer

2.4 Friend function Categories:

Depending on the source of this function, there are three ways to do this:

Common function Friend function

Purpose: To enable ordinary functions to access the friend of a class

Grammar:

Disclaimer: Friend + common function declaration

Implementation location: Can be outside the class or in a class

Implementation code: Same as normal function

Call: Similar to normal function, call directly

 @file point.cc//@author Alexcthon ([email protected])//@date 2018-06-12 09:40:14//#include < math.h> #include <iostream>using std::cout;using std::endl;class point{public:point (int ix = 0, int iy = 0): _ix (i x), _iy (iy) {cout << point (int=0, int=0) << Endl;} void print () const{cout << "(" << _ix << "," << _iy << ")" << Endl;} int GetX () const {return _ix;} int GetY () const {return _iy;} Friend's common function friend float distance (const point & LHS, Const point & RHS);p rivate:int _ix;int _iy;}; #if 0float Distance (const point & LHS, Const Point & RHS) {return sqrt ((Lhs.getx ()-RHS.GETX ()) * (Lhs.getx ()-RH S.getx ()) + (Lhs.gety ()-rhs.gety ()) * (Lhs.gety ()-rhs.gety ()));} #endif float Distance (const point & LHS, Const Point & RHS) {return sqrt ((lhs._ix-rhs._ix) * (Lhs._ix-rhs._ix) + (Lhs._iy-rhs._iy) * (Lhs._iy-rhs._iy));} int main (void) {point pt1 (1, 2); Point Pt2 (3, 4); cout << "Pt1 and PTDistance between 2: "<< distance (pt1, pt2) << Endl;return 0;} 

 

class Y a member function for the class X the friend function

Purpose: to make a member function of Class y a friend of Class X, specifically: In this member function of Class Y, with the help of parameter x, you can directly use the private variable of x

Grammar:

Declaration location: Declared in public (itself as a function)

Declaration: Friend + Declaration of member function

Call: Define Y's Object y---use y to call your own member function---Use the friend mechanism in your own member function

Code:

#include <math.h> #include <iostream>using std::cout;using Std::endl;class point;//class forward declaration class line{ Public:float Distance (const point & LHS, Const point & RHS);}; Class Point{public:point (int ix = 0, int iy = 0): _ix (ix), _iy (iy) {cout << "point (int=0, int=0)" << Endl;} void print () const{cout << "(" << _ix << "," << _iy << ")" << Endl;} member function friend float line::d istance (const-point & LHS, const-point & RHS);p rivate:int _ix;int _iy;}; #if 0float Distance (const point & LHS, Const Point & RHS) {return sqrt ((Lhs.getx ()-RHS.GETX ()) * (Lhs.getx ()-RH S.getx ()) + (Lhs.gety ()-rhs.gety ()) * (Lhs.gety ()-rhs.gety ()));} #endif float Line::d istance (const-point & LHS, const-point & RHS) {return sqrt ((lhs._ix-rhs._ix) * (LHS._IX-RHS . _ix) + (lhs._iy-rhs._iy) * (Lhs._iy-rhs._iy));} int main (void) {point pt1 (1, 2); Point Pt2 (3, 4); Line Line;cout << "distance between Pt1 and pt2:" << line.distance (pt1, pt2) << Endl;return 0;} 

  

class Y all of the member functions are class X friend function - Friend class

Purpose : Use a single declaration to make all functions of the Y Class A friend of Class X, which provides a way to collaborate between classes so that objects of class Y can have the functions of Class X and Class Y.

Grammar:

Declaration location: Public private can, often write as private (the class as a variable)

Declaration: Friend + class name (not object)

Add: When using a friend member function, be aware of the interdependence between the friend declaration and the friend definition. The predecessor declaration of the class.

#include <math.h> #include <iostream>using std::cout;using Std::endl;class point;//class forward declaration class line{ Public:float Distance (const point & LHS, Const Point & RHS), void setpoint (int ix, Int. iy, Point & PT);p rivate: int _iz;}; Class Point{public:point (int ix = 0, int iy = 0): _ix (ix), _iy (iy) {cout << "point (int=0, int=0)" << Endl;} void print () const{cout << "(" << _ix << "," << _iy << ")" << Endl;}  Friend//friend class Line;friend line;//must be broken class encapsulation//friend is unidirectional, not transitive, cannot inherit////a, B, B, C ==> A, cvoid Setz (line & line, int iz) {//point cannot access the private member of line Line._iz = iz;} Private:int _ix;int _iy;};  Float line::d istance (const-point & LHS, const-point & RHS) {return sqrt ((lhs._ix-rhs._ix) * (Lhs._ix-rhs._ix) + (lhs._iy-rhs._iy) * (Lhs._iy-rhs._iy));} void Line::setpoint (int ix, int iy, point & PT) {Pt._ix = Ix;pt._iy = iy;} int main (void) {point pt1 (1, 2); Point Pt2 (3, 4); Line Line;cout << "pt1 andDistance between pt2: "<< line.distance (pt1, pt2) << Endl;line.setpoint (5, 6, pt1); cout <<" pt1 = ";p t1.print (); RET Urn 0;}

Summary: in fact, some of the overloaded implementation of the operator is to be implemented outside the class, then usually, the declaration as a friend of the class is a must drop.

4. The difference between a friend function and a member function of a class

  all member functions of a friend class are friend functions of another class and can access hidden information in another class, including private members and protected members. When you want a class to be able to access the private members of another class, you can declare the class as a friend of another class.

  the member function has this pointer, and the friend function does not have the this pointer . In fact, as with static member functions, static member functions do not have this pointer, so it can only access static member variables or access non-static member variables through objects.

A friend class is one-way, non-transitive, and cannot be inherited .

Class rect  {public  :  rect ()      //constructor, counter plus 1  {  count++;  }  Rect (const rect& r)//{//width = R.width;//height = R.height;//count++;//}~rect ()     //destructor, counter minus 1  {  count--;  }  static int GetCount ()       //Returns the value of the counter  {  return count;  } friend int get ();p rivate:  int width;  int height;  static int count;       A static member is made as a counter  };  int rect::count = 0;        To initialize the counter, the static member variable must be initialized outside the class int get () {return rect::count;//friend function accesses the private static member variable through the class}int main ()  {  Rect rect1;  cout<< "The Count of Rect:" <<rect::getcount () <<endl;//accesses the public static member function through the class, outputting 1  Rect rect2 (rect1);   Using Rect1 to copy the Rect2, there should be two objects at this time  cout<< "The Count of Rect:" <<rect::getcount () <<endl; Output 1cout << get () << endl;//output 1//cout << rect::count << endl;//cannot compile through and cannot access private members. This can only access non-static member variables or member functions in the class system ("pause"); return 0;  }  

Note: How do you understand that a friend class is one-way, non-transitive, and cannot be inherited?

1, Friend class can not be inherited. This is not much to say, it is easy to understand.

2, Friend class is one-way. A->b,b->a? This is wrong.

3, Friend class is not transitive. A->b,b->c, a=>c? This is wrong.

Add: When the class has a lot of member variables, you need to provide a lot of get/set methods to implement member variable access, in this case, it may be possible to UF the method of the element.

third, operator overloading (using friend functions)
@file    complex.cc  //@author Alexcthon ([email protected])//@date    2018-06-12 10:10:03//#include <iostream>using std::cout;using std::endl;class Complex{public:complex (double dreal = 0, double dimag = 0): _dreal ( Dreal), _dimag (dimag) {}void display () {cout << _dreal << "+" << _dimag << "i" << Endl;} The form of the member function Complex operator+ (const Complex & RHS) {return Complex (_dreal + rhs._dreal, _dimag + rhs._dimag);} Private:double _dreal;double _dimag;}; int main (void) {Complex C1 (1, 2); Complex C2 (3, 4); Complex C3 = C1 + C2;c3.display (); Complex C4 = c1 + 5;//c1.operator+ (5); C4.display (); Complex c5 = 5 + c1;//operator+ (5, C1); C5.display (); return 0;}

  

For more details on operator overloading, refer to this blog: https://www.cnblogs.com/cthon/p/9181404.html

C + + 's friend mechanism (friend function and friend Class)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.