In C, a friend function can access the private members of a class without becoming a member function of the class. In a template class, the declaration of a friend function is similar to the declaration in a normal class and must be declared outside the class definition. For example, to declare the friend function printValue in the template class MyClass, you need to declare the function outside the class definition using the friend keyword. A friend function can only access members of the class in which it is declared a friend.
C Detailed explanation of friend functions: use in template classes
Introduction
A friend function is a special type of function in C that is allowed to access private members of a class without becoming a member function of the class. Friend functions are useful in certain situations, such as when data or functionality needs to be shared across class boundaries.
Friend functions in template classes
Declaring friend functions in a template class is very similar to that in a normal class. The following example shows how to declare a friend function printValue
in template class MyClass
:
template <typename T> class MyClass { public: T value; friend void printValue(const MyClass<T>& obj) { std::cout << "Value: " << obj.value << std::endl; } };
Using friend functions
To use a friend function, the function must be declared outside the definition of the class. You can use the friend
keyword to specify a friend function, as shown below:
template <typename T> void printValue(const MyClass<T>& obj);
Practical case
Suppose we have a Node
Template class, which contains private data members value
, and wants to declare a friend function display
to display the value of the node.
template <typename T> class Node { public: T value; friend void display(const Node<T>& node) { std::cout << "Node Value: " << node.value << std::endl; } };
When writing friend functions, you need to pay attention to the following points:
const
or virtual
modifiers. The above is the detailed content of Detailed explanation of C++ friend functions: How to use friend functions in template classes?. For more information, please follow other related articles on the PHP Chinese website!