Friend Concept: A technical method that follows a certain rule to enable a software system other than an object to directly access the encapsulated data member in an object without being passed through the message is a friend.
As long as an outside object is described as a friend of a class, the outside object can access the private members of the class object.
An external object declared as a friend can be either a member function of another class, a generic function that does not belong to any class, or an entire class (so that all member functions in this class become friend functions).
1. Friend function
First, a piece of code, let us see the use of friend function!
#defineStrmax 32#include<iostream>#include<string>using namespacestd;classmyclass{intx, y; Char*string; Public: MyClass (intVxintVyChar*str) {x=VX; Y=VY; string=New Char[Strmax]; strcpy (string, str); } //friend int sum (MyClass C1);};intsum (MyClass C1) {returnc1.x+c1.y;}intMain () {MyClass C1 (Ten,Ten,"my MyClass object!"); cout<<"The sum is:"<<sum (C1) <<Endl; return 0;}
The compilation results are as follows:
Compiling ...
Friend1.cpp
F:\c++\friend1.cpp: Error C2248: ' x ': Cannot access private member declared in class ' MyClass '
F:\c++\friend1.cpp (7): See Declaration of ' X '
F:\c++\friend1.cpp: Error C2248: ' y ': cannot access private member declared in class ' MyClass '
F:\c++\friend1.cpp (7): see Declaration of ' Y '
Error executing cl.exe.
Friend1.exe-2 error (s), 0 warning (s)
Because the object accesses the private member variable, the compilation will fail!
Now remove the comment, the code is as follows:
#defineStrmax 32#include<iostream>#include<string>using namespacestd;classmyclass{intx, y; Char*string; Public: MyClass (intVxintVyChar*str) {x=VX; Y=VY; string=New Char[Strmax]; strcpy (string, str); } friendintsum (MyClass C1);};intsum (MyClass C1) {returnc1.x+c1.y;}intMain () {MyClass C1 (Ten,Ten,"my MyClass object!"); cout<<"The sum is:"<<sum (C1) <<Endl; return 0;}
The compilation passes, and the result is the sum is:20
2. Friend member
The member function of another class, as a friend of a class, is simply to add the class name of the member function where the friend function is declared, called the friend function.
3. Friend class
A class can be a friend of another class, so that all member functions in a class that are friends can access all members of the class that declare it as a friend class.
Friend mechanism in C + +