C++用类模板重载<<出现Link2019的解决
尝试用类模板实现对树的操作时候,重载<<出现LINK2019先直接上源码:
#include<iostream>
using std::cout;
using std::endl;
namespace data_type {
template<class T>
struct Data
{
T x;
T y;
};
}
class Node
{
public:
/*指针接口*/
Node<T>* leftson;//左儿子
Node<T>* rightson;//右儿子
data_type::Data<T> data;//存储的数据形式
/*函数接口*/
friend std::ostream& operator<<(std::ostream& os, Node<T>& node);
Node<T>() { };
Node<T>(T x, T y);
};
template<class T>
inline Node<T>::Node(T x, T y)
{
data.x = x; data.y = y;
}
template<class T>
std::ostream& operator<<(std::ostream& os, Node<T>& node)
{
os << "(" << node.data.x << "," << node.data.y << ")";
return os;
// TODO: 在此处插入 return 语句
}
int main() {
Node<int> node(10,10);
cout<<node<<endl;
return 0;
}
在该情况下编译会出现LINK2019。
主意到类模板友元函数在类外实现时和函数类模板类似,因此把
friend std::ostream& operator<<(std::ostream& os, Node<T>& node) {
os << "(" << node.data.x << "," << node.data.y << ")";
return os;
// TODO: 在此处插入 return 语句
};
这段实现直接放到类内,编译就成功通过了。