Home >Backend Development >C++ >Detailed explanation of C++ friend functions: How to use friend functions for cross-class access?
Friend functions in C allow non-member functions to access private and protected members of a class, which is very useful in implementing cross-class operations, ADT and unit testing: Declaring friend functions: Use the friend keyword to declare an out-of-class function. Use friend functions: Directly access a private member of a class as if it were a member function. Practical case: Use friend function to obtain private age information without exposing the age attribute.
In C programming, friend function is a powerful mechanism that allows Functions outside a class access private and protected members of the class. This is very useful in some situations, such as:
class MyClass { public: // ... private: // ... friend void print_my_class(const MyClass&); // 声明友元函数 };
The above code declares print_my_class
as a friend function of MyClass
. This means that the print_my_class
function can access private and protected members of MyClass
.
To use friend functions, you only need to directly access the private members of the class in the friend function:
void print_my_class(const MyClass& obj) { std::cout << "Private member: " << obj.private_member << std::endl; std::cout << "Protected member: " << obj.protected_member << std::endl; }
Suppose we have a Person
class, representing a person, which has a private age
member. We want to create a friend function get_age
to get the age of the Person
object:
class Person { public: // ... private: int age; friend int get_age(const Person&); // 声明友元函数 }; int get_age(const Person& person) { return person.age; }
In the main
function, we create a Person
object and use the friend function get_age
to access its private members:
int main() { Person person(25); std::cout << "Age: " << get_age(person) << std::endl; return 0; }
Output:
Age: 25
The above is the detailed content of Detailed explanation of C++ friend functions: How to use friend functions for cross-class access?. For more information, please follow other related articles on the PHP Chinese website!