我正在为我的学校做一个项目(我还是个初学者),我遇到了以下问题:
"[Error] no match for 'operator==' (operand types are 'Vehicle' and 'const Vehicle')" Vehicle是我项目中的一个类。
这就是给我的错误:
int DayLog::findWaitingPosistion(Vehicle const& v){
if (find(waitingList.begin(),waitingList.end(),v) != waitingList.end())
return 1;
}waitingList是Vehicle对象的向量。
我搜索了一下,但没有找到答案,尽管有很多和我相似的问题,我试了所有的方法,但都没有用。提前谢谢。
发布于 2016-01-28 07:34:25
使用find的最低要求是指定的operator==函数。这就是std::find在遍历向量时所使用的,如果它找到了您的类型。
像这样的东西将是必要的:
class Vehicle {
public:
int number;
// We need the operator== to compare 2 Vehicle types.
bool operator==(const Vehicle &rhs) const {
return rhs.number == number;
}
};这将允许您使用find。查看live example here.
发布于 2016-01-28 07:29:51
错误信息非常清楚:编译器正在寻找一个比较两辆车的operator==函数。这样一个方法的签名,如果它存在的话,应该是这样的
bool operator==(const Vehicle& first, const Vehicle& second);不清楚的是为什么会发生这种情况。毕竟,您没有在代码中的任何地方使用==运算符!糟糕的编译器--抱怨你甚至没有做过的事情。
要理解发生了什么,你必须理解“find”方法。这是一种模板方法,在C++中,模板是超级花哨的文本查找和替换(警告:大规模简化!)。“find”的代码将在编译器运行之前为您正在使用的类型动态生成。
您可以查看find是如何在here中实现的。在cplusplus.com离线的情况下,我已经包含了下面的相关部分*
template<class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val)
{
while (first!=last) {
if (*first==val) return first; //<--- Notice the == operator
++first;
}
return last;
}这就是==的由来!编译器将自动为您指定的类型(vehicle)生成find代码。然后,当它进行编译时,生成的代码会尝试使用operator==,但没有用于车辆的an。您将不得不为您的vehicle类提供一个。
*说真的- check out that website。它向你展示了所有这些东西是如何工作的。
https://stackoverflow.com/questions/35050065
复制相似问题