Home > Backend Development > C++ > Detailed explanation of C++ friend functions: When do you need to use friend functions?

Detailed explanation of C++ friend functions: When do you need to use friend functions?

WBOY
Release: 2024-04-29 09:12:02
Original
1153 people have browsed it

A friend function is a non-member function that has access to private or protected members. Friend functions can be used to facilitate cross-class data sharing, access private members to implement specific functions, and allow external functions to access class private data, etc.

C++ 友元函数详解:何时需要使用友元函数?

#C Detailed explanation of friend functions: When to use friend functions?

What is a friend function?

Friend functions are non-member functions that allow access to private or protected members. Friend functions are not part of the class but have access to private members of the class.

When to use friend functions?

Using friend functions is convenient in the following situations:

  • Access private members to implement specific functions.
  • Cross-class data sharing.
  • Allow external functions to access class private data.

Syntax

The syntax for declaring a friend function is as follows:

friend 返回类型 函数名(参数列表);
Copy after login

friend The keyword is used to specify the function is a friend function.

Practical Case

Consider the following code, which defines a class with a private member data:

class MyClass {
private:
    int data;
public:
    // ...
};
Copy after login

Now, We need a friend function to access the data member in order to modify it:

friend void modifyData(MyClass& obj, int newData) {
    obj.data = newData;
}
Copy after login

The modifyData function is declared as a friend function, so it can access the class Private member data of MyClass.

Note

  • Use friend functions with caution, as they bypass the principle of encapsulation.
  • Friend functions can only access private or protected members, but cannot access class private methods.
  • Friend functions are not part of the class, so this pointers cannot be used.

The above is the detailed content of Detailed explanation of C++ friend functions: When do you need to use 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