Home  >  Article  >  Backend Development  >  Detailed explanation of the friend mechanism of C++ functions

Detailed explanation of the friend mechanism of C++ functions

WBOY
WBOYOriginal
2024-04-18 11:15:021108browse

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

C++ 函数的友元机制详解

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:

  • Allow non-member functions to access private members of a class
  • Allow member functions of a class to access private members of another class

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn