【问题标题】:LNK 2019 Error when trying to overload the "<<" opeartorLNK2019 尝试重载“<<”运算符时出错
【发布时间】:2016-05-07 12:08:59
【问题描述】:

我有一个模板类MGraph&lt;T&gt;,它有一个成员函数print_relation 和一个朋友函数ostream&amp; operator&lt;&lt;(ostream&amp; os, const MGraph&lt;T&gt;&amp; 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&gt;main.obj : error LNK2019: unresolved external symbol "class std::basic_ostream&lt;char,struct std::char_traits&lt;char&gt; &gt; &amp; __cdecl operator&lt;&lt;(class std::basic_ostream&lt;char,struct std::char_traits&lt;char&gt; &gt; &amp;,class MGraph&lt;bool&gt; const &amp;)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$MGraph@_N@@@Z) referenced in function "void __cdecl exec&lt;bool&gt;(class MGraph&lt;bool&gt; *)" (??$exec@_N@@YAXPAV?$MGraph@_N@@@Z)

它出现 4 次,每种数据类型一次(intchardoublebool)。

我做错了什么?

【问题讨论】:

标签: c++ templates operator-overloading


【解决方案1】:

operator&lt;&lt; 的超载中,你正在这样做

os &lt;&lt; other.print_relation(os);

因为MGraph&lt;T&gt;::print_relation 返回std::ostream&amp;,所以这是无效的。 operator&lt;&lt; 没有以这种方式重载,它在 RHS 上占用 std::ostream&amp;

所以,只需删除 os &lt;&lt;

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

【讨论】:

  • 谢谢。那我需要传递参数os吗?
  • 没关系。我删除了 operator&lt;&lt; 作为类中友元函数的声明,现在它可以工作了。
猜你喜欢
  • 2014-03-18
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多