Friend functions can modify the private properties of a class, written under the public/private/protected of the class. When the function body of a friend function is written outside the class, it does not need to add the Friend keyword, just like a normal function, but the function entry parameter is usually a pointer to a class or a reference to a class to use the class's private properties.
A friend class has the same function as a friend function. When a class A is declared a friend class of another class B, Class A can access the private properties of Class B. The function entry parameters in Class A generally have a pointer to Class B or a reference to Class B.
For example:
1 //. h file2 #pragmaOnce3 classMyteacher4 {5 Public:6Myteacher (void);//no parameter constructor7Myteacher::myteacher (intAConst Char* N);//Parametric Constructors8Myteacher (Constmyteacher&);//copy Constructor9~myteacher (void);Ten voidPrintt (void); OneFriendvoidModifyt (Myteacher&,int,Const Char*); AFriendclassMystudent;//Mystudent is a friend of the Myteacher class that can access private properties in Myteacher - - Private: the intAge ; - Charname[ +]; - }; - + - classmystudent + { A Public: atMystudent (ints); - voidPrintt (myteacher&); - - Private: - intscore; - }; in - to + //. cpp Files -#include"Myteacher.h" the#include <string.h> *#include <iostream> $ Panax Notoginseng //no parameter constructor -Myteacher::myteacher (void) the { +Age= -; Astrcpy (Name,"Li"); the } + - //Parametric Constructors $Myteacher::myteacher (intAConst Char*N) $ { -Age=A; - strcpy (name,n); the } - Wuyi //copy Constructor theMyteacher::myteacher (Constmyteacher&T) - { WuAge=T.age; - strcpy (name,t.name); About } $ - //Print function - voidmyteacher::p rintt () - { Astd::cout<<age<<Std::endl; +std::cout<<name<<Std::endl; the } - $ the // Destructors theMyteacher::~myteacher (void) the { the } - in //friend function the voidModifyt (myteacher& PT,intAge,Const Char*PN) the { AboutPt.age =Age ; the strcpy (Pt.name, PN); the } the + -Mystudent::mystudent (ints= -) the {BayiScore=s; the } the - voidMystudent::p Rintt (myteacher&t) - { thestd::cout<<"Age :"<<t.age<<Std::endl; thestd::cout<<"Name:"<<t.name<<Std::endl; the } the - the //Main function the#include <iostream> the#include"Myteacher.h"94 the using namespacestd; the the 98 intMain () About { -Myteacher T ( -,"Wu");101 T.printt ();102 103Modifyt (T, -,"Chen");104 T.printt (); the 106Mystudent S (98);107 S.printt (t);108 109System"Pause"); the return 0;111}
Friend function and friend class in C + +