实现重载运算符'<<'时出错 - C++
Error when implementing overloaded operator '<<' - C++
我当前正试图重载'<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<;""链接列表.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件事你可以做
- 请确保
fetchData()
返回的类型具有<<
的重载。C++本机类型和字符串类型(在<string>
中)已经具有此功能。如果它是自定义类型,则必须为该类型编写重载 - 从
fetchData
返回一个字符串。这样,就可以在<string>
中为<<
使用std::string
过载
正如我之前所说,在不知道fetchData()
返回了什么的情况下,很难说这里出了什么问题。
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 如何显式调用运算符<<
- 模板操作员&lt;未打电话
- C / CUDA中的模板方法是3个角括号(&lt;&lt;&lt;)
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个
- 为什么“操作员”需要const但不是为“运营商&lt;”
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 左角支架解释为操作员&lt;而不是模板参数
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- 超载操作员&lt;&lt; - 必须是二进制操作员
- 没有匹配的“运营商&lt;&lt;”