Home > Article > Backend Development > When do you need to use friend functions?
Scenarios for using friend functions in C include: 1. Operator overloading; 2. Cross-class access; 3. Global functions; 4. Testing. Friend functions can access private members of other classes, but they reduce encapsulation, so use them sparingly only when necessary and make sure to provide only the necessary access.
When to use friend functions
In C, a friend function is a special function that can access a certain Private and protected members of a class. In certain situations, using friend functions can provide convenience and flexibility.
Use occasions
or -
operator. Syntax
The syntax for declaring a friend function is as follows:
friend 返回值类型 函数名(参数列表);
The syntax for declaring a class as a friend is as follows:
class 类名 { // ... friend 返回值类型 函数名(参数列表); // ... };
Practical case
Consider a Date
class representing a date, which has private members day
, month
and year
. Now, we want to implement a isLeapYear
function to check whether the specified year is a leap year.
class Date { private: int day, month, year; public: // ... friend bool isLeapYear(int year); }; bool isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }
In this case, the friend function isLeapYear
can access the private member year
of the Date
class in order to calculate whether it is a leap year .
Other notes
The above is the detailed content of When do you need to use friend functions?. For more information, please follow other related articles on the PHP Chinese website!