Home > Article > Backend Development > Detailed explanation of C++ friend functions: What problems are friend functions used to solve?
Friend functions are special functions in C that can access private members of other classes. They solve the access restrictions caused by class encapsulation and are used to solve problems such as data operations between classes, global function access to private members, and code sharing across classes or compilation units. Usage: Use the friend keyword to declare a friend function to access private members. Note: Use friend functions with caution to avoid errors caused by bypassing the encapsulation mechanism. Use only when necessary, limit access, and use modifier functions sparingly.
C Detailed explanation of friend function: a powerful tool for lifting access restrictions
Introduction
Friend function is a special type of function in C that can access private members of another class. It allows data and methods that are originally inaccessible to the outside world to be accessed by the outside world, thus solving the access restriction problems caused by some class encapsulation.
Purpose
Friend functions are usually used to solve the following problems:
Syntax
The syntax for declaring a friend function is as follows:
class ClassName { // ...成员声明 friend FunctionName; };
where FunctionName
is the friend function The name.
Practical case
Suppose we have two classes Student
and Teacher
, they need to access each other's private data . We can use friend functions to achieve this:
class Student { private: int marks; }; class Teacher { private: int salary; public: friend void calculateBonus(const Student& student, const Teacher& teacher); }; void calculateBonus(const Student& student, const Teacher& teacher) { std::cout << "Student's marks: " << student.marks << std::endl; std::cout << "Teacher's salary: " << teacher.salary << std::endl; } int main() { Student student; student.marks = 90; Teacher teacher; teacher.salary = 50000; calculateBonus(student, teacher); return 0; }
In this example, the calculateBonus
function is declared as a friend of the Student
and Teacher
classes metafunction, so it can access the private members marks
and salary
of these two classes.
Usage Precautions
You need to be careful when using friend functions, because they bypass the encapsulation mechanism of the class and may cause unexpected errors. Therefore, the following points should be considered when declaring friend functions:
The above is the detailed content of Detailed explanation of C++ friend functions: What problems are friend functions used to solve?. For more information, please follow other related articles on the PHP Chinese website!