Home > Article > Backend Development > Can a C++ function be declared as a friend function? What are the characteristics of friend functions?
Yes, C functions can be declared as friend functions. Friend functions have the following properties: They can access private and protected members of a class. You cannot directly access the this pointer of a class. Can be defined outside the scope of the class. It is not a member function of the class and does not belong to the interface of the class.
Friend functions are non-member functions that have access to private and protected members of a class. Friend functions can access data encapsulated in other classes and are very useful in special situations.
In C, friend functions can be declared in two ways:
Global friend function:
friend void myFunction(classA& object);
Member friend function:
class classA { friend void classB::myFunction(classA& object); };
Friend functions have the following characteristics:
Suppose we have a Counter
class, which represents a counter. Its private member is an integer representing the count count
.
class Counter { private: int count; public: Counter(int c) : count(c) {} };
We want to create a friend function increment
that can increase the value of the counter.
friend void increment(Counter& c) { c.count++; }
Now, we can use friend functions to increment the counter value:
int main() { Counter c(0); increment(c); cout << c.count << endl; // 输出 1 return 0; }
Friend functions are a powerful feature in C that can provide access to private and Access rights for protected members. They can be declared in two ways and are useful in special cases, such as when private data needs to be accessed from other classes.
The above is the detailed content of Can a C++ function be declared as a friend function? What are the characteristics of friend functions?. For more information, please follow other related articles on the PHP Chinese website!