【问题标题】:Compiler error message with cout带有 cout 的编译器错误消息
【发布时间】:2011-10-03 09:11:36
【问题描述】:

我之前打错了错误信息。现已修复。

我目前收到以下编译器错误消息

error: no match for 'operator<<' in 'std::cout << Collection::operator[](int)(j)'

编译器抱怨的代码是

cout << testingSet[j];

其中testingSetCollection 类型的对象,它具有operator[] 重载以返回Example 类型的对象。 Example 有一个友元函数,它为 ostream 和 Example 重载 operator&lt;&lt;

注意:这实际上在 Visual Studio 中编译得很好;但是不使用 g++ 编译。

这里是operator&lt;&lt;的实现:

ostream& operator<<(ostream &strm, Example &ex)
{
     strm << endl << endl;
     strm << "{ ";
     map<string, string>::iterator attrib;
     for(attrib = ex.attributes.begin(); attrib != ex.attributes.end(); ++attrib)
     {
          strm << "(" << attrib->first << " = " << attrib->second << "), ";
     }
     return strm << "} classification = " << (ex.classification ? "true" : "false") << endl;
}

还有operator[]

Example Collection::operator[](int i)
{
      return examples[i];
}

【问题讨论】:

  • 不要描述你认为的实现是什么 - 发布实际的实现。显然不是你想的那样。
  • 您能否为我们指明std::Collection 的文档方向?我以前没有遇到过 C++ 标准库的这一部分。
  • (另外,我会努力改掉写using namespace std的习惯,改写std::ostreamstd::cout的习惯)。
  • 那么到底为什么它会被std:: 限定呢?见stackoverflow.com/q/320798/78845
  • 可以发一下operator[]的实现吗?

标签: c++ compilation compiler-errors stdio


【解决方案1】:

可能你的操作符应该声明为:

ostream& operator<<(ostream &strm, const Example &ex)

注意对示例的 const 引用。 Visual Studio 有一个扩展,它允许将引用绑定到非常量 r 值。我的猜测是您的 operator[] 返回一个 r 值。

无论如何,operator&lt;&lt; 应该是 const,因为它不会修改写入的对象。

【讨论】:

  • 是的,但是我不能像我在实现中那样使用迭代器。我该如何解决这个问题?
  • 使用map&lt;string, string&gt;::const_iterator attrib;?你不是在修改对象,是吗?
  • 啊哈!就是这样。我不知道 const_iterator。谢谢!
  • 哦,对不起,有点过激了。我实际上仍然收到错误:(
  • 啊,不过现在已经修复了。使operator[] 返回const string 是最后的润色。
猜你喜欢
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-12
相关资源
最近更新 更多