Home > Backend Development > C++ > body text

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

WBOY
Release: 2024-04-16 08:57:02
Original
815 people have browsed it

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);
Copy after login

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:
    // ...
};
Copy after login

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;
}
Copy after login

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;
}
Copy after login

Output:

Data: 42
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!