通常當我做一個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