C + + learning 12 friend function and friend class

Source: Internet
Author: User
Tags ming

Friend functions and friend classes are less used in actual development, and readers who want to learn C + + quickly can skip this section.

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 add an exception to this-friend (friend).

In C + +, this relationship is declared by the key friend, and the Chinese is translated into friends. Friends can access private members in classes with which they have friends, including friend functions and friend classes. If you are not accustomed to the name of friends, you can understand as friends by the original friend.

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.

The friend function can access all members of the current class, including the private property.

1) Declare the normal function as a friend function.

#include <iostream>using namespacestd;classstudent{Private:    Char*name; intAge ; floatscore; Public: Student (Char*,int,float); FriendvoidDisplay (Student &);//declaring display as a friend function}; Student::student (Char*name,intAgefloatscore) {     This->name =name;  This->age=Age ;  This->score =score;}//Ordinary member functionsvoidDisplay (Student &Stu) {cout<<stu.name<<"The Age is"<<stu.age<<", the results are"<<stu.score<<Endl;}intMain () {Student stu ("Xiao Ming", -,95.5f);    Display (STU); return 0;}

Note that display is a function that is defined outside the class and is not qualified with Student, which is a non-member function and does not belong to any class, it is the function of outputting the student's information. If the display function is not declared in the Student class as a friend function, it cannot refer to the private member in Student name, age, score.

Now that the display is a friend function of the Student class, display can use the private member in Student name, age, score. Note, however, that these member variables must be prefixed with an object name and cannot be written as:

cout<<name<<"" <<age<<""<< score<<endl;

Because display is not a member function of the Student class, the members of the Student class cannot be used by default, and you must specify the object to access.

2) Declare member functions of other classes as friend functions
The friend function can be not only a normal function (non-member function), but also a member function in another class. Take a look at the following example:

#include <iostream>using namespacestd;classAddress;//Declaration of advance references to the address class//declaring the Student classclassstudent{Private:    Char*name; intAge ; floatscore; Public: Student (Char*,int,float); voidDisplay (Address &);};//declaring the address classclassaddress{Private:    Char*Province; Char*City ; Char*District; Public: Address (Char*,Char*,Char*); //declare the member function display in the student class as a friend functionFriendvoidStudent::d isplay (Address &);}; Address::address (Char*province,Char*city,Char*District) {     This->province =Province;  This->city =City ;  This->district =District;}//declaring the student class as constructors and member functionsStudent::student (Char*name,intAgefloatscore) {     This->name =name;  This->age=Age ;  This->score =score;}voidStudent::d isplay (Address &add) {cout<<name<<"The Age is"<<age<<", the results are"<<score<<Endl; cout<<"Home Address:"<<add.province<<"Province"<<add.city<<"City"<<add.district<<"Area"<<Endl;}intMain () {Student stu ("Xiao Ming", -,95.5f); Address Add ("Shaanxi","Xian","Yanta");    Stu.display (add); return 0;}

In this example, two classes Student and Address are defined. The 26th line of the program declares the member function display in the Student class as a friend function, so that display can access the private member variable of the Address class.

Two points Note:
The address class was declared in the 4th line of the ① program because it was used in the student class before the address class was defined, and if it was not declared in advance, the compilation would 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 declarations and definitions of the Student class, and puts the address in the middle because Student: a member of the address class is used in the body of the:d isplay () function, which must appear after the class body of the address class (the class body describes which members are)

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 scope of advance declaration of a class is limited. You can use it to create an object only after you have formally declared a class. If you add a line after the 4th line of the above program:

After declaring a class in advance, you can use the name of the class to define a reference variable to a pointer variable or object of that type object (as in this example, the reference variable for the Address class object is defined). This is because the size of the pointer variable and the reference variable itself is fixed, regardless of the size of the class object it points to.

Note that the program is formally declared in the Address class before the definition Student::d isplay () function. This is because the member variables province, city, district of the address class are used in the Student::d isplay () function body, and the compiler cannot recognize these member variables if the address class is not formally declared.

③ a function can be declared as a "friend" by more than one class, so that it can refer to private members in multiple classes.

Friend class

Not only can you declare a function as a "friend" of a class, but you can declare an entire class (for example, Class B) as a "friend" of another class (for example, Class A). In this case, Class B is a Class A friend.

All functions in the friend Class B are friend functions of Class A and can access all members of Class A. Declare Class B as its friend class in Class A with the following statement:

Friend B;

The general form of declaring a friend class is:

Friend class name;

About friend, there are two points to note:

    • A friend's relationship is one-way rather than two-way. If the class B is declared a friend of Class A, not equal to Class A is a friend of Class B, the member function in Class A cannot access private data in Class B.
    • Friend relationship can not be passed, if Class B is a Class A friend class, Class C is a friend Class B, not equal to Class C is a class A friend class.

In real-world development, it is safer to declare the entire class as a friend unless it is necessary, rather than declaring the member function as a friend function, which is really necessary.

C + + learning 12 friend function and friend class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.