【发布时间】:2016-05-07 12:08:59
【问题描述】:
我有一个模板类MGraph<T>,它有一个成员函数print_relation 和一个朋友函数ostream& operator<<(ostream& os, const MGraph<T>& other)
我按照here 的说明编写了以下代码:
template<class T>
ostream& MGraph<T>::print_relation(ostream& os) const
{
for (VertexId i = 0; i < max_size; i++)
{
for (VertexId j = 0; j < max_size; j++)
{
os << relation[i][j] << ' ';
}
os << endl;
}
return os;
}
...
template<class T>
ostream& operator<<(ostream& os, const MGraph<T>& other)
{
os << other.print_relation(os);
return os;
}
编译时出现以下错误:
1>main.obj : error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class MGraph<bool> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$MGraph@_N@@@Z) referenced in function "void __cdecl exec<bool>(class MGraph<bool> *)" (??$exec@_N@@YAXPAV?$MGraph@_N@@@Z)
它出现 4 次,每种数据类型一次(int、char、double、bool)。
我做错了什么?
【问题讨论】:
-
你把函数的定义(实现)放在源文件还是头文件中?
-
在包含的头文件中
-
如果将模板化类和函数的实现放在源文件中,通常会出现类似的错误。另见"Why can templates only be implemented in the header file?"。
标签: c++ templates operator-overloading