Friend function
Global functions or other class member functions can be declared as friend functions, and the private functions of the class can be used inside the friend function Member
#includeusing namespace std;class CCar; //Declare the CCar class in advance so that the following CDriver class can use class CDriver{public: void ModifyCar( CCar* pCar); //Modify a car}; class CCar{private: int price; friend int MostExpensiveCar(CCar cars[], int total); //Declare a friend friend void CDriver::ModifyCar(CCar* pCar); / /Declare a friend);void CDriver::ModifyCar(CCar* pCar){ pCar->price += 1000; //value increase after car modification}int MostExpensiveCar(CCar cars[], int total) //seeking the most expensive The price of the car {int tmpMax = -1; for (int i = 0; i tmpMax) tmpMax = cars[i].price; return tmpMax;}int main(){ return 0;}
Friend class
A class A can declare another class B as its friend , All member functions of class B can access the private members of class A objects
Affinity cannot be inherited, only granted to the Class
class CCar{private: int price; friend class CDriver; //declare CDriver as a friend class}; class CDriver{public: CCar myCar; void ModifyCar() //Modify a car {myCar.price += 1000; //Because CDriver is a friend class of CCar, its private members can be accessed here}};int main(){ return 0;} pre>