Home > Backend Development > C++ > What type members can C++ friend functions access?

What type members can C++ friend functions access?

王林
Release: 2024-04-15 17:09:01
Original
925 people have browsed it

In C, friend functions can access all public, protected, and private members of a class, but access to private members is restricted and can only be done when a member function of the class is called.

C++ 友元函数能访问哪些类型成员?

#C What type members can a friend function access?

What is a friend function?

A friend function is a special function in C that can access private and protected members of a class. Friend functions must be declared outside the class definition.

Type members that friend functions can access

Friend functions can access the following type members:

  • public members: Friend functions can access all public members of the class.
  • protected members: Friend functions can access all protected members of the class.
  • Private members: Friend functions can access private members of a class, but only when the friend function is called by a member function of the class.

Practical case

Consider the following code:

class MyClass {
private:
    int m_num;

public:
    MyClass(int num) : m_num(num) {}

    friend void print_num(MyClass& obj) {
        std::cout << obj.m_num << std::endl;
    }
};

int main() {
    MyClass obj(42);
    print_num(obj);  // 友元函数访问私有成员
    return 0;
}
Copy after login

Output result:

42
Copy after login

In this example, print_num () is a friend function of MyClass. It can access the private member m_num even though it is not a member function of MyClass.

Restricted Access

It should be noted that the access of friend functions to private members is restricted. Friend functions can only access private members when a member function of the class is called. In other words, friend functions cannot directly access private members from the outside.

The above is the detailed content of What type members can C++ friend functions access?. 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