Home  >  Article  >  Backend Development  >  How do C++ friend functions access private members?

How do C++ friend functions access private members?

WBOY
WBOYOriginal
2024-04-15 17:27:02677browse

There are two ways for friend functions in C to access private members: declare the friend function within the class. Declare a class as a friend class so that all member functions in the class can access the private members of another class.

C++ 友元函数如何访问私有成员?

C Friend function’s method of accessing private members

A friend function is defined outside the class but can be accessed Functions of private members of the class. There are two ways to implement friend functions' access to private members:

1. Declare a friend function

Declare a friend function within the class, the syntax is as follows:

class ClassName {
public:
  // 类成员...

  // 声明友元函数
  friend void friend_function();
};

In this way, the declared friend function can access the private members of the class.

2. Declare a friend class

Declare a class as a friend class, and all member functions in the class can access the private members of another class. The syntax is as follows:

class ClassName1 {
public:
  // 类成员...

  // 声明友元类
  friend class ClassName2;
};

All member functions declared in ClassName2 can access the private members of ClassName1.

Practical case

Consider the following C code:

class Person {
private:
  int age;
  string name;

public:
  // 友元函数
  friend void print_person_info(const Person& person);

  // 访问私有成员的友元函数
  void print_info() const {
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
  }
};

// 友元函数外部分类的定义
void print_person_info(const Person& person) {
  cout << "Name: " << person.name << endl;
  cout << "Age: " << person.age << endl;
}

int main() {
  Person person;
  person.name = "John";
  person.age = 30;

  person.print_info();
  print_person_info(person);

  return 0;
}

In this example, the print_person_info function is a friend function , which has access to private members of the Person class. In the Person class, the print_info function also accesses private members, which uses a friend function declaration.

Running the above code will output:

Name: John
Age: 30
Name: John
Age: 30

The above is the detailed content of How do C++ friend functions access private members?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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