The friend mechanism allows a class to grant access to its non-public members to a specified function or class . General friend declaration with keyword friend start .
Friends can only appear inside a class definition . The declaration of a friend can appear anywhere in the class . In general, friend declarations are placed in batches at the beginning or end of a class definition . The simplest example of using friend mechanism is as follows :
class Screen { friend class Windows ; ...... }

In the example above , class Windows Is declared as a class Screen Friend class of , After that, in the class Windows Classes can be used in Screen The non-public resources of China , Including its private members . Friends can be ordinary non member functions , Member functions of other classes or the entire class .

stay ISO/IEC
14882:2003(E) in , A friend of a class or class template can be a function template or a class template . Friend templates can be created in classes ( Or class template ) Internally declared . Friend function can be used in class ( Or class template ) Defined in , However, a friend class template cannot be in a class ( Or class template ) Is defined in .

Friend definitions in class templates are mainly divided into the following categories 3 class :

* Non templated function , Class as friend of instance class ;
* template function , Template class as friend of same type instance class ;
* template function , Class as a friend of different types of instance classes .
The following are examples .

(1) Non templated function , Class as friend of instance class . Examples are as follows :
class A{ void AF(); }; template <class Type> class Queue { friend class B;
// class B No prior declaration is required friend void A(); // function A() friend void A::AF(); // class A It must be declared in advance }
(2 ) template function , Template class as friend of same type instance class . Examples are as follows :
template <class Type> class A{...}; template <class Type> void D() (B <Type>);
template <class Type> class C{ void Cf();...}; template <class Type>class B {
friend class A<Type>; // template class A It needs to be defined or declared first friend void D(B <Type>); // template function A() It needs to be defined or declared first
friend void C<Type>::Cf(); // template class C Must be defined first };
(3) template function , Class as a friend of different types of instance classes . Examples are as follows :
template <class T>class B { friend<class Type>friend class A; template <class
Type>friend void D(B <Type>); template <class Type>friend void C::Cf(); }

Technology