A class can have members of public, protected, private three properties that can access public members, and only functions in this class can access private members of this class. Now, let's introduce an exception-friend (friend). with friend, you can make member functions in other classes and functions in the global scope access the private members of the current class.
Fnend means friends, or friends, and the relationship with friends is obviously more intimate than the average person. We will open our hearts to good friends, confide in their secrets, and cautious to the average person, the subconscious self-protection. In C + +, this friendly relationship can be indicated by the Friend keyword, which is translated into "friend", and a friend can access a private member in a class that has a friend relationship. If you are not accustomed to the term "friend", you can understand it as a friend by the source.
Friend function
Functions that are not part of the current class that are defined outside of the current class can also be declared in the class, but the Friend keyword is added before, which makes up the friend function. A friend function can be a non-member function that is not part of any class, or it can be a member function of another class.
A friend function can access all members of the current class, including public, protected, and private properties.
1) Declare the non-member function as a friend function.
Please look directly at the following example:
#include <iostream>using namespacestd;classstudent{ Public: Student (Char*name,intAgefloatscore); Public: FriendvoidShow (Student *pstu);//declare show () as a friend functionPrivate: Char*M_name; intM_age; floatM_score;}; Student::student (Char*name,intAgefloatscore): M_name (name), M_age (age), M_score (score) {}//non-member functionsvoidShow (Student *pstu) {cout<<pstu->m_name<<"The Age is"<<pstu->m_age<<", the results are"<<pstu->m_score<<Endl;}intMain () {Student stu ("Xiao Ming", the,90.6); Show (&STU);//Adjust the function of the UF elementStudent *pstu =NewStudent ("Li Lei", -,80.5); Show (PSTU); //Adjust the function of the UF element return 0;}
Operation Result:
Xiaoming's age is 15, the score is 90.6.
Li Lei's age is 16, the score is 80.5.
Show () is a global scoped non-member function that does not belong to any class, and it is useful for outputting student information. M_name, M_age, M_score are private members of the Student class, which in principle cannot be accessed through objects, but must be used in the show () function, so the show () is declared as a friend function of the Student class. The reader can test it himself, delete the 8th line of the above procedure and observe the error message of the compiler.
Note that the friend function differs from the member function of the class, and the members of the class cannot be accessed directly in the friend function, and must be aided by the object. The following syntax is incorrect:
void Show () { cout<<m_name<<""<<m_age<< " "<<m_score<<Endl;}
The member function implicitly increments the this pointer on invocation, points to the object that invokes it, uses the member of the object, and show () is a non-member function, without the this pointer, and the compiler does not know which object to use, and if you want to make this clear, you must pass the object by argument (you can pass the object directly. You can also pass an object pointer or object reference, and specify the object when accessing the member.
2) Declare member functions of other classes as friend functions
The friend function can be not only a global function (non-member function), but also a member function of another class. Take a look at the following example:
#include <iostream>using namespacestd;classAddress;//declare the address class in advance//declaring the Student classclassstudent{ Public: Student (Char*name,intAgefloatscore); Public: voidShow (Address *addr);Private: Char*M_name; intM_age; floatM_score;};//declaring the address classclassaddress{Private: Char*m_province;//Provinces Char*m_city;//City Char*m_district;//District (urban area) Public: Address (Char*province,Char*city,Char*district); //declare the member function in the Student class show () as a friend functionFriendvoidStudent::show (Address *addr);};//implementing the Student classStudent::student (Char*name,intAgefloatscore): M_name (name), M_age (age), M_score (score) {}voidStudent::show (Address *addr) {cout<<m_name<<"The Age is"<<m_age<<", the results are"<<m_score<<Endl; cout<<"Home Address:"<<addr->m_province<<"Province"<<addr->m_city<<"City"<<addr->m_district<<"Area"<<Endl;}//implementing the Address classAddress::address (Char*province,Char*city,Char*District) {m_province=Province; M_city=City ; M_district=District;}intMain () {Student stu ("Xiao Ming", -,95.5f); Address Addr ("Shaanxi","Xian","Yanta"); Stu.show (&addr); Student*pstu =NewStudent ("Li Lei", -,80.5); Address*PADDR =NewAddress ("Hebei","Hengshui","Taocheng"); Pstu-Show (PADDR); return 0;}
Operation Result: Xiao Ming's age is 16, the score is 95.5 home address: Xi ' an city, Shaanxi province Yanta District Li Lei's age is 16, the result is 80.5 home address: Hebei Province Hengshui Taocheng District
This example defines two classes Student and Address, and the program 27th will declare the member function of the Student class as the friend function of the address class, so that show () can access the private member variable of the address class.
Note: The address class is declared in advance in line 4th of the ① program because it is used in the Student class before the address class is defined, and if it is not declared beforehand, the compiler will give an error, prompting ‘Address‘ has not been declared . the advance declaration of the class and the advance declaration of the function is a good idea.
The ② program separates the Declaration and implementation of the Student class, and puts the declaration of the Address class in the middle, because the compiler compiles the code from top to bottom, and the show () function body uses the address member province, city, district, if you don't know in advance Address, you cannot determine whether the address owns the member (the class's declaration indicates which members of the class).
Here is a brief description of the class's advance declaration. In general, a class must be used after a formal declaration, but in some cases (as in the previous example), it can be used first as long as it is declared in advance.
It should be noted, however, that the use of a class's advance declaration is limited and can only be used to create objects after a class is formally declared. If a statement such as the following is added after line 4th of the above program, the compiler will error:
Address addr; An attempt was made to create an object using an incomplete class
Because the object is to be allocated memory when it is created, the compiler cannot determine how much memory should be allocated to the object before formally declaring the class. The compiler can determine how much memory should be reserved for an object only after the formal declaration of the "See" Class (in fact, the member variable is seen). After declaring a class in advance, you can use the name of the class to define a pointer variable to that type of object (this example defines a pointer variable for the Address Class) or a reference variable (which is described later) because the size of the pointer variable and the reference variable itself is fixed, regardless of the size of the data it points to.
③ a function can be declared as a friend function by more than one class, so that it can access private members in multiple classes.
Friend class
Not only can you declare a function as a "friend" of a class, but you can also declare an entire class as a "friend" of another class, which is the Friends class. All member functions in a friend class are friend functions of another class.
For example, if Class B is declared as a friend of Class A, all member functions in class B are friend functions of Class A that can access all members of Class A, including public, protected, private properties.
Change the code in the previous example to declare the Student class as a friend of the Address class:
#include <iostream>using namespacestd;classAddress;//declare the address class in advance//declaring the Student classclassstudent{ Public: Student (Char*name,intAgefloatscore); Public: voidShow (Address *addr);Private: Char*M_name; intM_age; floatM_score;};//declaring the address classclassaddress{ Public: Address (Char*province,Char*city,Char*district); Public: //declaring a student class as a friend of the address classFriendclassStudent;Private: Char*m_province;//Provinces Char*m_city;//City Char*m_district;//District (urban area)};//implementing the Student classStudent::student (Char*name,intAgefloatscore): M_name (name), M_age (age), M_score (score) {}voidStudent::show (Address *addr) {cout<<m_name<<"The Age is"<<m_age<<", the results are"<<m_score<<Endl; cout<<"Home Address:"<<addr->m_province<<"Province"<<addr->m_city<<"City"<<addr->m_district<<"Area"<<Endl;}//implementing the Address classAddress::address (Char*province,Char*city,Char*District) {m_province=Province; M_city=City ; M_district=District;}intMain () {Student stu ("Xiao Ming", -,95.5f); Address Addr ("Shaanxi","Xian","Yanta"); Stu.show (&addr); Student*pstu =NewStudent ("Li Lei", -,80.5); Address*PADDR =NewAddress ("Hebei","Hengshui","Taocheng"); Pstu-Show (PADDR); return 0;}
The 24th line of code declares the Student class as a friend of the Address class, declaring the statement as:
class Student;
Some compilers may not write the class keyword, but it is recommended to improve compatibility.
About friend, there are two points to note:
- A friend's relationship is one-way rather than two-way. If Class B is declared to be a friend of Class A, it does not mean that class A is a friend of Class B, and member functions in Class A cannot access private members in Class B.
- A friend relationship cannot be passed. If Class B is a friend of Class A, Class C is a friend of Class B, not equal to Class C, which is a friend class of Class A.
Unless necessary, it is generally not recommended to declare the entire class as a friend class, but only some member functions are declared as friend functions, which is more secure.
Original link: http://c.biancheng.net/cpp/biancheng/view/211.html
C + + friend function and friend Class (GO)