The understanding of C + + friend functions and friend classes __ function

Source: Internet
Author: User

1, the definition and function of friend function

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. 2, the above access is not direct access, for ordinary private member variables are accessed through the object, for private static variables are accessed through the class.

Why not direct access to it.

Let's take a look at why member functions directly access member variables.

A member function can access a member variable of a class because it passes the this pointer to the current object, which is meaningful if it accesses data members of the object to which this is this point.

The friend function is not a member function and is not passed the hidden this pointer and can only be accessed indirectly.

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.

Example:

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 ();
Private:  
	int width;  
	int height;  
	static int count;       A static member is done as a counter  
};  

int rect::count = 0;        Initialize counter  
int get ()
{return
	rect::count;//friend function Access private static member variable through class
}
int main ()  
{  
	Rect Rect1;  
	cout<< "The Count of Rect:" <<rect::getcount () <<endl;//access to public static member functions via class, outputting 1  

	Rect rect2 (rect1);   Using Rect1 to copy rect2, there should be two objects  
	cout<< "The Count of Rect:" <<rect::getcount () <<endl; Output 1
	cout << get () << endl;//output 1
	//cout << rect::count << endl;//cannot compile and access private members
	System ("pause");
	return 0;  
}  
3, the friend relationship between the class and the class cannot be inherited.

Below reproduced from:

http://blog.csdn.net/shandianling/article/details/7469361

C + + Primer has the following description: The friend relationship can not inherit. A friend of a base class has no special access to a member of a derived class
Permissions. If the base class is granted a friend relationship, only the base class has special access rights, and the derived class of the base class cannot access the class that is granted the friend relationship.

In practice, however, the VS compiler does not install the description described above, and the following rules contradict the above description but conform to the VS compiler's processing rules.

Note: The g++ compiler is needed to verify this.

1 inheritance problems with friend class

1.1derived class C of friend B of Class A cannot access private or protect member variables of Class A. But you can access a by using the interface provided by B. (nonsense definitely can) [CPP]  View Plain  copy #include  <iostream>    using namespace    std;    class b;    class a    {        int a;    public:        a (int  x=0)  { a=x; }        friend class B;    };    class b    {        int  b;    public:        void fun (a& ob) {  cout << ob.a << endl;}    };       class c:public b   {    public:        //void fun2 (a& ob) {&NBSP;COUT&NBSP;&LT;&LT;OB.A  <<endl;}    //the newly added function of a derived class does not access a, this sentence is reportedError   };       void   main ()     {        a a (;   )     C c;        c.fun (a);  //c is a derived class B     can still access    }  through a function of base class B fun   


Friends of 1.2. base can access the Private,protect member variable of base through the derived class drived base, but cannot access drived private,protect member variables. (This seems to be a bit of a conflict with "C + + Primer")

Personal understanding: The DriveD object itself contains the Base,base friend Frnd can naturally access the base part.

[CPP] view plain copy #include <iostream> using namespace std;    Class Base {int m_a;        public:base (int x=0) {m_a=x;}    Friend class Frnd;       }; Class Drived:public Base {private:int m_c;

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.