Home  >  Article  >  Backend Development  >  Detailed explanation of C++ friend functions: Application of friend functions in STL?

Detailed explanation of C++ friend functions: Application of friend functions in STL?

王林
王林Original
2024-04-30 08:42:01524browse

In C, a friend function is a special function that can access private members of other classes. The declaration of a friend function uses the friend keyword, and you need to pay attention to access permissions when defining it. Friend functions are used extensively in the STL to allow container classes to interact with algorithms, such as std::swap(), std::ostream_iterator, and std::vector.

C++ 友元函数详解:友元函数在STL中的应用?

C Detailed explanation of friend function

What is a friend function?

Friend function is a special function that can access private members of other classes. It allows data sharing and manipulation across classes.

Friend function declaration

Friend functions can be declared using the friend keyword:

class MyClass {
private:
    int x;
public:
    friend void printX(MyClass& obj);
};

Friend Function definition

Friend functions can be defined like normal functions, but you need to pay attention to access permissions:

void printX(MyClass& obj) {
    cout << obj.x << endl;
}

Practical case: Friend functions in STL

The Standard Template Library (STL) makes extensive use of friend functions to allow container classes to interact with algorithms:

1. std::swap()

std::swap() function used to exchange two container elements is a friend function because it needs to access the private members of the container:

template<typename T>
void swap(T& a, T& b) {
    // ... 交换 a 和 b 的私有成员 ...
}

2 . std::ostream_iterator

The std::ostream_iterator class used to output container elements uses friend functions to access the begin() and end() Method:

template<class T>
class ostream_iterator {
friend ostream& operator<<(ostream& os, const ostream_iterator<T>& it);
};

3. std::vector

std::vector class uses friends function to access its internal implementation:

template<typename T>
class vector {
friend class std::allocator<T>;
};

Conclusion

Friend functions are powerful tools in C that allow sharing data and performing operations across classes. Friend functions are used extensively in STL to enable seamless interaction between containers and algorithms.

The above is the detailed content of Detailed explanation of C++ friend functions: Application of friend functions in STL?. 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