Friend functions in C ++ classes and friends

Friend function
friend function is a non-member function directly access private members of the class. It is defined outside the class of ordinary functions, it does not belong to any class, but need to be declared in the class definition, just add a keyword before the name of the friend of the friend declaration in the following format:
friend type function name (formal parameters);
[Note] the private part of the declaration of a friend function class can be placed, can be placed on the public part, which is no different, is a friend are described for the class.
Function may be a function of a plurality of friend classes, each statement only in each class.
Way calling and call general functions and friend functions consistent principle.
E.g:

class A
{
	...
public:
   friend void B(int c);
   ...
};

Friend class
of Friends of all member functions yuan class are another class friend function, you can access the hidden information in another class (including private members and protected members).
When you want a class can access private members of another class, the class can be declared as a friend class in another class. Friend class defined statement format is as follows:
Friend class class name;
[Note] (1) friend and class are keyword, class name must be a program that is already defined classes.
(2) friend relationship can not be inherited.
(3) friend relationship is unidirectional, not commutative. If class B is a friend of class A, class A is not necessarily a friend of class B, depending on whether there is a corresponding statement in the class.
(4) friendship is not transitive. If class B is a friend of class A, class B is a friend of C, C is not necessarily the friend class A, if a corresponding class depends likewise stated
example:

class A
{
...
public:
 friend class B;
 ...
};

The role of
the role of friend is to improve the efficiency of the program (a reduction of type checking and security checks and so need time overhead), but it undermines the encapsulation and hidden class, making the non-member function can access private class member.

发布了14 篇原创文章 · 获赞 15 · 访问量 4865

Guess you like

Origin blog.csdn.net/weixin_44480968/article/details/104472715