通常当我做一个std :: find时,我会把一个谓词作为第三个参数,但是这次我想我会以不同的方式做它,不明白为什么它不起作用。为什么不能这个std :: find比较这些对象
#include <iostream>
#include <vector>
#include <algorithm>
struct RenderJob
{
RenderJob() {};
int renderJob_ID;
bool operator==(RenderJob& rhs) { return rhs.renderJob_ID == this->renderJob_ID; }
};
int main()
{
RenderJob foo;
RenderJob foo2;
foo == foo2; // Works
std::vector<RenderJob> renderJobs;
std::find(renderJobs.begin(), renderJobs.end(), foo); // Doesn't work
}
二进制“==”无操作员发现这需要 类型RenderJob的左手操作数(或没有可接受的转化率)
编辑::嗯谢谢你的答案。下面是一些例子,为什么失败
RenderJob foo;
RenderJob foo2;
foo == foo2; // Works
std::vector<RenderJob> renderJobs;
std::vector<RenderJob>::const_iterator constit = renderJobs.begin();
*constit == foo2; // Doesn't work
即使作为说明简单:
const RenderJob* pToRenderJob;
*pToRenderJob == foo2; // This fails because the pointed to
// object is const, and cannot call the
// operator== function because the actual function
// definition is not const.
如果它是周围的其他方法:
foo2 == *pToRenderJob; // This would fail because the
// operator==(RenderJob&) the actual argument
// is not const. Very subtle rules
在您的示例中,您不能执行'* constit == foo2'或'* pToRenderJob == foo2',因为'operator =='没有声明为允许'const'左操作数变为'* this' 。如果类有一个函数'void f();' - 你不能'constit-> f()'或'pToRenderJob-> f()',那将是同样的事情。但是如果你把这个函数改成'void f()const;',那两个都没问题。 – aschepler
谢谢,许多规则正在缓慢设置中。 – Zebrafish
您还应该在类中定义'renderJob_ID':'int renderJob_ID {}'。离开未初始化的对象是过早的优化。在你的例子中,foo.renderJob_ID和foo.renderJob_ID有* indeterminate value *,如果你声明'std :: vector renderJobs(10)'创建10个'renderJobs'的向量,所有这10个对象的renderJob_ID将拥有一个*不确定的值*。因此,即使在将const添加到运算符==参数后,您的代码仍然无法工作。 –
Oliv