且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

模板类,朋友操作符<超载

更新时间:2023-11-11 21:08:10

根据,您必须将功能称为模板,在您的类定义。

According to this, you have to make the function known as template in your class definition.

class.h

#include <iostream>
using std::ostream;

template <typename T>
class A {
  public:
    ...

    template <typename J> // <-- CAUTION!
    friend ostream &operator<<(ostream &output, const A<J> &a);
};

class.cpp

#include "class.h"
...
template <typename T>
ostream &operator<<(ostream &output, const A<T> &a) {
  // Your implementation
  return output;
}

...
template ostream &operator<<(ostream &output, const A<int> &a);
template ostream &operator<<(ostream &output, const A<float> &a);

如果行 template< typename J> 被删除,编译错误underfined reference。

If the line template <typename J> is removed, the compilation error "underfined reference" comes.