我有一个MGraph<T>
带有成员函数print_relation
和一个朋友函数的模板类,它是ostream& operator<<(ostream& os, const MGraph<T>& other)
我按照此处的说明进行操作并编写了以下代码:
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
)。
我做错什么了?
在的超载中operator<<
,您正在执行此操作
os << other.print_relation(os);
并且由于MGraph<T>::print_relation
return std::ostream&
,这是无效的。operator<<
不会以std::ostream&
RHS的方式过载。
因此,只需删除os <<
。
template<class T>
ostream& operator<<(ostream& os, const MGraph<T>& other)
{
other.print_relation(os);
return os;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句