Home >Backend Development >C++ >How to use friend functions in class templates?

How to use friend functions in class templates?

WBOY
WBOYOriginal
2024-04-17 10:36:01515browse

Use friend functions in class templates to allow external functions to access private members. Steps: Declare a friend function: Use the "friend" keyword in the class template. Define friend functions: Use the type parameters of the class template to make it applicable to all types. Use friend functions: Call friend functions just like calling ordinary member functions.

How to use friend functions in class templates?

Use friend functions in class templates

Use friend functions in class templates to allow external functions to access the class template Private member. Here's how to declare and use friend functions in a class template:

#include <iostream>

template <typename T>
class MyClass {
private:
  T data;

public:
  // 声明友元函数
  friend void print(const MyClass<T>& object);

  // 成员函数
  void set_data(const T& value) { data = value; }
};

// 友元函数定义
template <typename T>
void print(const MyClass<T>& object) {
  std::cout << "Data: " << object.data << std::endl;
}

int main() {
  MyClass<int> obj;
  obj.set_data(10);
  print(obj);  // 调用友元函数

  MyClass<std::string> strObj;
  strObj.set_data("Hello!");
  print(strObj); // 调用友元函数

  return 0;
}

Output:

Data: 10
Data: Hello!

The above is the detailed content of How to use friend functions in class templates?. 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