The friend function in C + + parses the _c language in detail

Source: Internet
Author: User
Tags class definition function definition cmath

Why to make the Ufida function

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

In fact, there are approximately two situations in which the friend function needs to be used: (1) Some occasions in which operator overloading requires the use of friends. (2) Two classes to share data.

Advantages and disadvantages of using friend functions

Advantages: can improve efficiency, simple and clear expression.

Disadvantages: friend function broken ring encapsulation mechanism, as far as possible not to use member functions, unless the case only to make Ufida function.

The friend mechanism in C + + allows the non-public members of a class to be accessed by a class or function, and the friends are grouped into three types: ordinary, non-class member functions as friends, members of classes as friends, and classes as friends. Friends include statements of friends and definitions of friends. The friend's declaration defaults to extern, that is, the scope of the friend class or friend function has been extended to the scope that contains the definition of the class, so even if we define a friend function within the class, it does not matter.

A friend can be a function called a friend function; A friend can also be a class, which is called a friend class. A friend function is characterized by the ability to access a member function of a private member in a class. A friend function is syntactically the same as a normal function, that is, it is defined and called as a normal function.

The implementation of a friend function can be defined outside the class, but must be declared inside the class

A friend function is a non-member function that can directly access a private member of a class. It is a normal function that is defined outside the class, and it does not belong to any class,

However, it needs to be declared in the definition of a class by adding the keyword friend to the friend's name only.

We already know that classes have an attribute of 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 also destroys the hidden attributes. In addition, you should see that in some cases, especially when multiple calls are made to some member functions, the time overhead is required because of parameter passing, type checking, and security checking, which affects the efficiency of the program.

In order to solve the above problems, this paper puts forward a scheme to make ufida. A friend is a generic function that is defined outside of a class, but it needs to be described in the class body, in order to differentiate it from the member functions of the class, and the keyword friend is preceded by the description. A friend is not a member function, but it can access private members in a class. The role of the friend is to increase the efficiency of the program (that is, to reduce the time overhead required for type checking and security checks), but it destroys the encapsulation and concealment of the class, allowing Non-members to access the private members of the class.

1. Ordinary non-member function friends

 #include "Cmath" #include "iostream" using namespace std; 
     Class Point {public:point (double xx,double yy) {x=xx; 
   Y=yy; 
   } void Getxy (); 
Friend Double Distance (Point &a,point &b); 
Protected:private:double X,y; 
}; 
   void Point::getxy () {//cout<< "(" <<this->x<< "," <<this->y<< ")" <<endl; 
cout<< "(" <<x<< "," <<y<< ")" <<endl; 
   Double Distance (Point &a,point &b) {double length;   Length=sqrt ((a.x-b.x) * (a.x-b.x) + (A.Y-B.Y) * (A.Y-B.Y)); 
It can refer to the private member in the class return length; 
   int main (void) {point P1 (3.0,4.0), p2 (6.0,8.0); P1.  Getxy (); The invocation method of a member function that invokes P2 by using an object. 
   Getxy ();   Double d = Distance (P1,P2); 
   Call method of a friend function, like a call to a normal function, do not call cout<<d<<endl; like a member function 
   System ("pause"); 
return 0; } 

Description: In the point class in the program, a friend function distance () is described, which adds the friend keyword in front of the description, identifying it as not a member function, but a friend function. It is defined in the same way as a normal function definition, and differs from the definition of a member function because it does not need to indicate the class to which it belongs. However, it can refer to private members in a class, and the a.x,b.x,a.y,b.y in the function body are private members of the class, which are referenced through objects. When you call the function, it is also the same as the normal function, do not call as a member function. In this case, p1. Getxy () and P2. Getxy () This is a call to a member function, to be represented by an object. and distance (P1, p2) is called the friend function, it is called directly, does not need the object representation, its argument is an object. (The program's function is known as two point coordinates, to find the distance of two points.) )

The following is an input to the above code and an overload of the output stream:

#include <cmath> #include <iostream> using namespace std; 
      Class Point {public:point (double xx,double yy) {x=xx; 
   Y=yy; 
   } void Getxy (); 
   Friend Double Distance (Point &a,point &b); 
Friend Ostream &operator << (ostream &a,point &b); 
Protected:private:double X,y; 
}; 
Friend ostream& operator<< (ostream& o,a& another); Ostream &operator << (ostream &out,point &b)//when declared in a class, can be Ostream &a, and the function definition can also be ostream & 
   Out {out<< "(" <<b.x<< "," <<b.y<< ")" <<endl; 
return out; 
   } void Point::getxy () {//cout<< "(" <<this->x<< "," <<this->y<< ")" <<endl; 
   cout<< "(" <<x<< "," <<y<< ")" <<endl; 
cout<<*this; 
   Double Distance (Point &a,point &b) {double length; 
   Length=sqrt ((a.x-b.x) * (a.x-b.x) + (A.Y-B.Y) * (A.Y-B.Y)); return LEngth; 
   int main (void) {point P1 (3.0,4.0), p2 (6.0,8.0); P1. 
   Getxy (); P2. 
   Getxy (); 
   Double d = Distance (P1,P2); 
   cout<<d<<endl; 
   System ("pause"); 
 
return 0; 
 }

2. Class as Friends

Classes as friends need to be aware of the interdependence between the friend class and the original class, and if the function defined in the Friend class uses the private variable of the original class, then the file in the friend class definition needs to contain the header file of the original class definition. However, in the definition of the original class (which contains the class declared by the friend Class), you do not need to include the header file for the friend class.

In addition, you do not need to declare a friend class before the class definition, because the declaration of a friend class is itself a declaration.

A.h  
#pragma once  
#include <iostream>  
using namespace std;  
Class A  
{  
  //friend class B;//If you do not write this sentence there will be a compilation error public 
:  
  ~a (void);  
  A (); 
Private:   
  int m_nitem; 
};  
A.cpp 
#include "A.h" 
 
a::a () 
{ 
  m_nitem =3; 
} 
 
A::~a (void) 
{ 
} 
//b.h 
#pragma once  
 
class B  
{public  
:  
  b (void);  
  ~b (void);  
  int func ();  
};  
B.cpp 
#include "StdAfx.h" 
 
#include "B.h"  
#include "A.h"//must include A.h  
#include < iostream> 
 
 
b::b (void) 
{ 
} 
 
b::~b (void) {} 
 
int b::func ()  
{  
  cout << "This are in B" <<endl;  
  A A; 
  return a.m_nitem; 
}  

3. class member functions as friend functions

This is a little bit complicated, because you want to class member functions as friends, you declare friends with the class qualifier, so you must first define the class containing the friend function, but in defining the function of the friend, you must define the original class. The usual practice is to define a class that contains a friend function, and then define the original class, which is not a messy order. (If it is a friend class, there is no such necessity) as follows:

A.h 
#pragma once 
#include "B.h" 
class A 
{ 
friend int b::func (a xx); 
Public: 
  A (void): MX (m) {} 
  ~a (void) {} 
private: 
  int mx; 
  int my; 
}; 
B.h 
#pragma once 
class A; 
Class B 
{public 
: 
  b (void); 
  ~b (void); 
  int func (A xx); 
}; 
B.cpp 
#include "B.h" 
#include "A.h" 
 
b::b (void) 
{ 
} 
b::~b (void) 
{ 
} 
int B::func (A xx) 
{return 
  xx.mx * xx.my; 
} 
Main.cpp 
#include "A.h" 
#include "B.h" 
#include <iostream> 
using namespace std; 
void Main () 
{ 
  a A; 
  b b; 
  Cout<<b.func (a) <<endl; 
  System ("pause"); 
} 

4. The friends do not have the reciprocity, only has the single sex

If Class B is a friend of Class A, class A is not necessarily a friend of Class B, to see if there is a corresponding declaration in the class.

5. Friends cannot be inherited

B is a friend of the class, C is a subclass of B, can't push out C is a friend

6. Friends do not have transitivity

B is a friend, C is a friend of B, can't push out C is a friend

7. The use of friend function skills

When you implement a singleton pattern in C + +, you can instantiate an object by using the friend function. The constructors and destructors of the class are then designed as private functions.

Class Cmysingleton 
{public 
: 
  friend cmysingleton& Instancemec (); 
 
Private: 
  Cmysingleton () {}; 
  Cmysingleton (const Cmysingleton &lxsington) {}; 
  ~cmysingleton () {}; 
}; 
 
cmysingleton& Instancemec () 
{ 
  //Because function Instancemec () is a friend function of class Clxsingletonmec, you can access all member functions of the class. So there's no compile error. 
  static Cmysingleton Instance;  
  return Instance; 
}  

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.