Home > Backend Development > C++ > body text

How to determine whether a function is a friend function?

PHPz
Release: 2024-04-15 15:09:01
Original
458 people have browsed it

Method to determine whether a function is a friend function: Use the keyword friend in the function declaration. Class name qualifiers are not required in function declarations.

How to determine whether a function is a friend function?

How to determine whether a function is a friend function

A friend function is not part of a class, but it can still be accessed Private member of the class. Friend functions can be determined in the following ways:

  1. Use the keyword friend
class MyClass {
private:
    int data;
    friend void printData(const MyClass& obj);
};
Copy after login

in the function declaration above In the example, the printData() function is a friend function because the keyword friend is used in its declaration.

  1. No class name qualifier is required in function declaration

Friend functions can be declared outside the class without using class name qualifiers:

class MyClass {
private:
    int data;
};

void printData(const MyClass& obj); // 友元函数声明
Copy after login
  1. Practical Case

Consider the following example showing how to use friend functions to access private members of a class:

class MyClass {
private:
    int data = 10;
    
    friend std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
        os << "data: " << obj.data;
        return os;
    }
};

int main() {
    MyClass obj;
    std::cout << obj << std::endl; // 输出:data: 10
    
    return 0;
}
Copy after login

In this example, the operator function is a friend function that is used to overload the output operator to customize the way information of the printing class is printed.

The above is the detailed content of How to determine whether a function is a friend function?. 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!