Home > Backend Development > C++ > body text

Detailed explanation of C++ friend functions: How to restrict the access rights of friend functions?

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

Friend functions in C can restrict access rights through access specifiers or namespaces to allow only specific functions or functions within a specific namespace to access private members of a class.

C++ 友元函数详解:如何限制友元函数的访问权限?

C Detailed explanation of friend functions: How to restrict the access rights of friend functions?

In C, a friend function is a special function that allows external functions to access private members of a class. It enables us to access private data or functions of one class outside another class, thus providing greater flexibility in certain situations.

Restrict the access rights of friend functions

We can limit the access rights of friend functions to private members by restricting friend declarations. There are two ways to do this:

Method 1: Using access specifiers

We can restrict using access specifiers (public, protected or private) Access permissions for friend functions. The syntax is as follows:

class MyClass {
  private:
    // 私有成员只能被友元函数访问
    friend void friendFunction();
};
Copy after login

Method 2: Use namespace

You can also use namespaces to limit the visibility of friend functions. The syntax is as follows:

namespace MyNamespace {
  class MyClass {
    private:
      // 私有成员由 MyNameSpace 命名空间内部所有友元函数访问
      friend class MyFriendClass;
  };
}
Copy after login

Practical case

Suppose we have the following two classes:

class Person {
  private:
    string name;
    int age;
};

class FriendClass {
  public:
    // 可以访问私有成员,因为它是一个友元类
    void printPersonDetails(Person person) {
      cout << person.name << ", " << person.age << endl;
    }
};
Copy after login

Here, FriendClass is A friend class of the Person class, so it can access private members such as name and age.

Run the example

int main() {
  Person person{"John Doe", 30};
  FriendClass friendObj;  
  friendObj.printPersonDetails(person);
  return 0;
}
Copy after login

Output:

John Doe, 30
Copy after login

The above is the detailed content of Detailed explanation of C++ friend functions: How to restrict the access rights of 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!