【问题标题】:no operator '>>' matches these operands [closed]没有运算符“>>”与这些操作数匹配[关闭]
【发布时间】:2015-09-13 20:42:01
【问题描述】:

我的程序无法编译,因为它没有找到操作数的匹配项。 它访问 struct Student 中的地图,我不确定这是否是访问地图的确切方式。

我的程序无法编译,因为它没有找到操作数的匹配项。 它访问 struct Student 中的地图,我不确定这是否是访问地图的确切方式。

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>
#include <map>
#include <list>


using namespace std;

struct Student {
    string id;
    map<string, int> scores;
};

istream& operator >>(istream &is, Sudent& g) {

    auto it = g.scores.begin();
    is >> g.id >> it->first >> it.second;
    return is;
}

&gt;&gt; it-&gt;first 我得到这个错误:

Error: no operator ">>" matches these operands
    operand types are: std::basic_istream<char, std::char_traits<char>> >> const std::string

【问题讨论】:

  • 请将代码发布为文本而不是图像。
  • @CaptainObvlious:这怎么可能有远近于复制的地方?
  • 查看istream的定义,运营商不行。

标签: c++ operator-overloading


【解决方案1】:

你可以使用临时变量

std::string tempStr;
int tempInt;
is >> g.id >> tempStr >> tempInt;
scores.insert( std::pair<std::string,int>(tempStr , tempInt));

【讨论】:

  • 正确的解决方案,但需要解释为什么 OP 的做法是错误的。没有解释的解决方案会导致货物崇拜行为。
【解决方案2】:

错误是因为it-&gt;first 的类型是const string,而不是string

除此之外,您还需要通过读取(未知)数量的字符串和相应的 int 来找到读取该映射的方法。如何做到这一点取决于它们在文件中的存储方式。

【讨论】:

  • 为什么it-&gt;first 会是constg 不是constg.scores 不是const,那么为什么会调用g.scores.begin()const 版本呢?使用auto 接受重载方法的返回值是否有副作用?将 auto 更改为 map&lt;string,int&gt;::iterator 应该可以修复错误。
  • it->first 是 const 因为在 map 中键是不可变的。允许更改它->首先意味着更改容器内对象的位置/顺序。这相当于删除/插入
  • 好的,谢谢你的信息。
猜你喜欢
  • 2023-01-27
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 2022-01-10
  • 2013-01-25
  • 1970-01-01
相关资源
最近更新 更多