Brief introduction of friend function and friend class _c language in C + + programming

Source: Internet
Author: User
Tags class definition

A class can have members of public, protected, private three attributes that can access public members through objects, and only functions in this class can access private members of this class. Now, let's add an exception--friend.

Fnend means a friend, or friends, who are obviously more intimate with their friends than the average person. Some families may do this: the living room is open to all visitors, and the bedroom, in addition to the members of the family can enter the person, but also allow good friends into. In C + +, this relationship with the key Yu friend statement, Chinese translation into friends. A friend can access a private member of a class with which it has friends, including friend functions and friend classes. If you are not accustomed to the term friend, you can follow the original friend to understand as friends.
friend function

Functions that are not part of the current class, defined outside the current class, can also be declared in a class, but are preceded by the Friend keyword, which constitutes a 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 private properties.

1 declare the normal function as a friend function.

#include <iostream>
using namespace std;
Class student{
private:
 char *name;
 int age;
 float score;
Public:
 Student (char*, int, float);
 friend void Display (Student &); Declare display as a friend function
};
Student::student (char *name, int age, float score) {
 this->name = name;
 This->age= age;
 This->score = score;
}
The age of the ordinary member function
void display (Student &stu) {
 cout<<stu.name<< is "<<stu.age<<", Score is "<<stu.score<<endl;
}
" int main () {
 Student stu ("Xiaoming", 95.5f);
 Display (stu);
 return 0;
}

Run Result:

Xiaoming's age is 16, and his grade is 95.5.

Note that display is a function defined outside the class that does not qualify with Student, which is a non-member function and does not belong to any class, and its function is to output the student's information. If the display function is not declared as a friend function in the Student class, it cannot refer to the private member name, age, and score in Student. You can take a close look at the 11th line in the above program and look at the compile-time information.

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

cout<<name<< "The Age is" <<age<< ", the result is" <<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 you want to access.

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

#include <iostream> using namespace std; class address;
 Advance Reference Declaration//Declaration of the Address class Student class student{Private:char *name;
 int age;
Float score;
 Public:student (char*, int, float);
void display (address &);
};
 Declare address class address{Private:char *province;
 Char *city;
Char *district;
 Public:address (char*, char*, char*);
Declare the member function display in the Student class as a friend function friend void Student::d isplay (address &);
};
 Address::address (char *province, Char *city, char *district) {this->province = province;
 this->city = City;
this->district = District;
 }//Declare Student class as constructors and member functions Student::student (char *name, int age, float score) {this->name = name;
 This->age= age;
This->score = score; } void Student::d isplay (Address &add) {cout<<name<< "Age is" <<age<< ", the result is" <<score
 <<endl; cout<< "Home Address:" <<add.province<< "Province" <<add.city<< "City" <<add.district<< "district"
<<endl; int main () {Student stu("Xiaoming", 95.5f);
 Address Add ("Shaanxi", "Xi ' an", "Yanta");
 Stu.display (add);
return 0;
 }

Run Result:

Xiaoming's age is 16, the result is 95.5
home address: Yanta District, Xi ' an city, Shaanxi province

In this example, two classes of Student and address are defined. Program 26th will declare 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 ① program Line 4th makes an advance declaration of the address class because it is used before the address class definition, in the student class, and if not stated in advance, the compilation complains, prompting "address" to has not been declared. The advance declaration of a class and the advance declaration of a function are a truth.

The ② program separates the declarations and definitions of the Student class, and places the address in the middle because the Student::d the Isplay () function body uses the address class members, which must appear after the class body of the address class (the class body describes which members).

Here is a brief description of the class's advance statement. Typically, a class must be used after a formal declaration, but in some cases (as shown in the previous example), it can be used first, as long as the declaration is made in advance.

It should be noted, however, that the scope of use of advance declarations of classes is limited. You can use it to create an object only after you have formally declared a class. If you add one line after line 4th of the above program:

Address obj; Attempt to define an object


An error occurs at compile time. Because an object is created to allocate memory space for an object, the compilation system cannot determine how much space should be allocated to the object before the class is formally declared. The compiler can only determine how much space should be reserved for an object when it sees the class body (in fact, it sees the member variable). After making a reference to a class, you can use the name of the class to define a reference variable to a pointer variable or object that points to that type of object (for example, in this case, a reference variable that defines the Address class object). 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 formally declares the address class before defining the Student::d isplay () function. This is because in the Student::d isplay () function body to use the address class of the member variable province, city, district, if not formally declared the address class, the compiler will not recognize these member variables.

③ a function can be declared as "friends" by multiple classes, so that you 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 (such as Class B) as a "friend" of another class (for example, Class A). Then Class B is the friend class of Class A.

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

Friend B;


The general form of the Declaration friend class is:

Friend class name;

For friends, there are two points to note:
The relationship between friends is one-way rather than two-way. If a class B is declared to be a friend of Class A, not equal to a friend class of Class B, a member function in Class A cannot access private data in Class B.
Friends of the relationship can not be passed, if the B class is a class of friends, Class C is a Class B friend class, not equal to C class is a friend class.

In actual development, it is more secure to declare the entire class as a friend only if it is necessary, rather than declaring it as a friends class.

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.