Home  >  Article  >  Backend Development  >  Can a C++ function be declared as a friend function? What are the characteristics of friend functions?

Can a C++ function be declared as a friend function? What are the characteristics of friend functions?

王林
王林Original
2024-04-19 22:12:01370browse

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.

C++ 函数可以声明为友元函数吗?友元函数的特性是什么?

#Can a C function be declared as a friend function? What are the characteristics of friend functions?

Friend functions

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.

Declare friend functions

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);
    };

Characteristics of friend function

Friend functions have the following characteristics:

  • 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.
  • is not a member function of the class and does not belong to the interface of the class.

Practical case

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;
}

Conclusion

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!

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