Friend function
The private properties of a default class can only be accessed directly within the class.友元函数申明在内的内部,实现在类的外部可以直接访问类的私有属性。
classa1{ Public: A1 () {a1 = -; A2 = $; }intGetA1 () {return This->a1; }//Declare a friend function friend voidSetA1 (A1 *p,intA1);//This function is a good friend of this class protected:Private:intA1;intA2;};voidSetA1 (A1 *p,intA1) {p->a1 = A1;}voidMain () {A1 mya1; Cout<<mya1.geta1 () <<endl; SetA1 (&MYA1, -);//Modify private properties of Class A with friend functionCout<<mya1.geta1 () <<endl; System"Pause");}
Add:
- The Friend function declaration statement location is independent of private and public.
- A friend function typically has parameters for that object, access private member property data through an object parameter
Friend class
- If Class B is a friend class of Class A, all member functions of Class B are friend functions of Class A
- A friend class is typically designed as an auxiliary class for passing messages between data operations or classes
C + + Development Series-friend function friend class