实现重载运算符'<<'时出错 - C++

Error when implementing overloaded operator '<<' - C++

本文关键字:lt C++ 出错 实现 运算符 重载      更新时间:2023-10-16

我当前正试图重载'<lt;'操作员,但一直收到这个错误消息:

在函数"std::ostream&运算符<lt;(std::ostream&,const:Linkedlist&)':Linkedlist.cpp:148:34:错误:"operator<lt;'在'std::operator<lt;[其中_CharT=char,_Traits=std::char_Traits,_Alloc=std::分配器](((std::basic_stream&)((std::ostream*)outs)),((const std::asic_string&lt;""链接列表.cpp:142:15:注意:候选者是:std::ostream&运算符<lt;(std::ostream&,const Linkedlist&)

重载的运算符函数在Linkedlist实现文件中被声明为友元成员函数,因为它将访问私有成员变量(head_ptr):

std::ostream& operator <<(std::ostream& outs, const Linkedlist& source)
{
    node* cursor;
    for(cursor = source.get_head(); cursor != NULL; cursor = cursor->fetchLink())
    {
        outs << cursor->fetchData() << " ";
    }
    return(outs);
}

这是Linkedlist头文件中的函数原型:

friend std::ostream& operator <<(std::ostream& outs, const Linkedlist& source);

我一直在网上搜寻,到目前为止还没能找到解决方案。任何建议都会很棒!

您的游标->fetchData()是否返回std::字符串?如果是,则必须#include <string>。或者,尝试

outs << cursor->fetchData().c_str() << " ";

对您未来可能发布的帖子的建议:如果您在问题中发布了部分代码,请发布所有相关的部分。目前,尚不清楚fetchData()返回了什么。

从外观上看,fetchData()似乎返回了对std::ostream::<<没有过载的东西。

当您输出到std::ostream实例时,所有组件都必须具有定义的行为。例如,在下面的示例中,为了使<<A的实例一起工作,运算符必须直接使用x,或者B需要定义一些行为,其中它推送一些标准ostream运算符已知的值。否则,您必须为链中的所有内容提供重载。

class B
{
friend std::ostream& operator<<(std::ostream& stream, const B& b);
int x = 10;
};
class A
{
private:
B b;
friend std::ostream& operator<<(std::ostream& stream, const A& a);
};
std::ostream& operator<<(std::ostream& stream, const B& b)
{
   stream << b.x;
   return stream;
}
std::ostream& operator<<(std::ostream& stream, const A& a)
{
   stream << a.b;
   return stream;
}
int main()
{
  A a;
  std::cout << a << "n";
  return 0;
}

我怀疑fetchData()返回的类型没有<<运算符的重载。这就是你看到失败的原因。

只有2件事你可以做

  1. 请确保fetchData()返回的类型具有<<的重载。C++本机类型和字符串类型(在<string>中)已经具有此功能。如果它是自定义类型,则必须为该类型编写重载
  2. fetchData返回一个字符串。这样,就可以在<string>中为<<使用std::string过载

正如我之前所说,在不知道fetchData()返回了什么的情况下,很难说这里出了什么问题。