Home > Article > Backend Development > Detailed explanation of the friend mechanism of C++ functions
C The friend mechanism allows non-member functions or classes to access private or protected members of other classes to achieve the following purposes: Allow non-member functions to access private members Allow member functions to access private members of other classes Allow class member functions to access another class Private members of a class
Detailed explanation of the friend mechanism of C functions
The friend mechanism is a method that allows functions or classes to access other Characteristics of private or protected members of a class or function. In C, the friend mechanism can achieve the following purposes:
Syntax
Global function friend declaration:
friend 返回值类型 函数名(参数列表);
Class friend declaration:
friend class 类名;
Class member function friend declaration:
friend 返回值类型 类名::成员函数名(参数列表);
Practical case:
Problem: Design a Point
class, which has private members x
and y
, and there is a print()
function that prints all private members. Now, we want an additional printInfo()
function that can access the private members of the Point
class and print them.
Implementation:
// Point 类 class Point { private: int x; int y; public: // 友元函数,可以访问 Point 类的私有成员 friend void printInfo(Point& point); // Point 类的成员函数 void print() { std::cout << "x: " << x << ", y: " << y << std::endl; } }; // 全局友元函数,可以访问 Point 类的私有成员 void printInfo(Point& point) { std::cout << "x: " << point.x << ", y: " << point.y << std::endl; } int main() { Point point{10, 20}; point.print(); // 输出:x: 10, y: 20 printInfo(point); // 输出:x: 10, y: 20 return 0; }
The above is the detailed content of Detailed explanation of the friend mechanism of C++ functions. For more information, please follow other related articles on the PHP Chinese website!