LNK 2019尝试重载“<<”时出错opeartor

时间:2016-05-07 12:09:00

标签: c++ templates operator-overloading

我有一个模板类var mongoose = require('mongoose'); module.exports = mongoose.model('Addsubject',{ classid: {type: mongoose.Schema.ObjectId, ref: 'Addclass' }, subject: String }); ,其成员函数MGraph<T>和友情函数print_relation

我按照说明here编写了这段代码:

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; }

它出现4次,每种数据类型一次(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) intchardouble)。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

在您operator<<的重载中,您正在执行此操作

os << other.print_relation(os);

由于MGraph<T>::print_relation返回std::ostream&,因此无效。 operator<<不会以这种方式重载,在RHS上需要std::ostream&

所以,只需删除os <<

template<class T>
ostream& operator<<(ostream& os, const MGraph<T>& other)
{
    other.print_relation(os);
    return os;
}