Home >Backend Development >C++ >What are the declaration rules for C++ friend functions?

What are the declaration rules for C++ friend functions?

WBOY
WBOYOriginal
2024-04-16 08:57:02956browse

The rules for declaration of friend functions are as follows: the declaration must be outside the class. Can be declared as a member function or global function. Objects of a class can be passed through pointers or references.

C++ 友元函数的声明规则有哪些?

C Declaration rules for friend functions

Friend function declaration

A friend function is a special function that can access private members of a class. To declare a friend function in C, use the friend keyword as follows:

// 声明 MyClass 类的友元函数 printInfo()
friend void printInfo(const MyClass& obj);

Declaration Rules

The following are in C Rules for declaring friend functions:

  • The declaration of a friend function must be outside the class.
  • Friend functions can be declared as member functions (with scope resolver) or global functions (without scope resolver).
  • Objects of a class can be passed through pointers or references.

Practical case

Consider the following MyClass class, which has private member variables _data:

class MyClass {
private:
    int _data;
public:
    // ...
};

We can define a friend function printInfo() to access _data:

// 声明 printInfo() 为 MyClass 的友元函数
friend void printInfo(const MyClass& obj) {
    std::cout << "Data: " << obj._data << std::endl;
}

In the main function, we can instantiate MyClass Object and call friend function to print private data:

int main() {
    MyClass obj;
    obj._data = 42;  // 访问私有成员(仅在友元函数中允许)
    printInfo(obj);  // 调用友元函数
    return 0;
}

Output:

Data: 42

The above is the detailed content of What are the declaration rules for C++ friend 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