我是一个 C++ 菜鸟,我搞不懂这个。我正在尝试使用模块参数作为键在 map 中搜索值,如下所示。我得到的第一个错误是下面所示行中的运算符等于不匹配,第二个错误是下面所示行中的“')' 标记之前的预期主表达式”。
float Student::getMark(const string &module) const throw (NoMarkException){ //TODO
map<string, float>::iterator p;
p = marks.find(module); //no match for operator=
if(p != marks.end())
return p->second;
else
throw (NoMarkException); //expected primary-expression before ')' token
return 0.0;
}
任何帮助将不胜感激!
最佳答案
您的成员函数被标记为 const
。这意味着您在函数中访问的所有成员也是 const
限定的。这意味着当您调用 find
时,它会返回一个 const_iterator
而不是 iterator
。您可以使用
map<string, float>::const_iterator p;
或者更容易
auto p = marks.find(module);
至于你抛出异常的错误,你应该创建一个对象来抛出。这意味着您需要 throw throw NoMarkException();
而不是 throw (NoMarkException);
关于c++ - 在 map 中搜索值时不匹配 'operator=',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41492478/