我希望标题能完整地描述我的问题。
运行代码出现错误:
error C2678: binary '==':no operator found which takes a left-hand operand of tpye 'A' (or there is no acceptable conversion)"
哪里出错了,我该如何解决这个问题???
class A
{
private: //Dummy Values
int x;
int y;
}
class B
{
private:
vector <A> dataHandler;
public:
bool isElement(A element);
//Should return true if element exists in dataHandler
}
bool B::isElement(A element)
{
int length = dataHandler.size();
for(int i = 0; i<length; i++)
{
if(dataHandler[i] == element) //Check if element is in dataHandler
return true;
}
return false;
}
最佳答案
在 isElement
中你有
if(dataHandler[i] == element)
这是尝试使用 operator==
比较两个 A
实例,但是您的 A
类没有实现任何此类运算符重载。您可能想要实现一个与此类似的
class A
{
private: //Dummy Values
int x;
int y;
public:
bool operator==(A const& other) const
{
return x == other.x && y == other.y;
}
};
此外,isElement
可以使用 std::find
重写而不是 for
循环
bool B::isElement(A const& element) const
{
return std::find(dataHandler.begin(), dataHandler.end(), element) != dataHandler.end();
}
关于c++ - 我想检查一个类实例是否已经存储在 std::vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30484156/