Error:
错误 C2678:二进制 '==':找不到采用 'const Entry' 类型的左侧操作数的运算符(或者没有可接受的转换)
功能:
template <class T, int maxSize>
int indexList<T, maxSize>::search(const T& target) const
{
for (int i = 0; i < maxSize; i++)
if (elements[i] == target) //ERROR???
return i; // target found at position i
// target not found
return -1;
}
索引列表.h http://www2.cs.uregina.ca/%7Emouhoubm/=teaching/=cs170/=indexList/indexList.h
索引列表.cpp http://www2.cs.uregina.ca/%7Emouhoubm/=teaching/=cs170/=indexList/indexList.cpp
这应该是一个重载的运算符吗?作为模板类,我不确定我是否理解该错误?
解决方案-
类中的重载函数现在声明为 const:
//Operators
bool entry::operator == (const entry& dE) const <--
{
return (name ==dE.name);
}
首先按原样阅读错误文本:
二进制“==”:找不到采用“const entry”类型的左侧操作数的运算符
这意味着找不到任何==
接受一个运算符entry
type 作为其左操作数。此代码无效:
entry const e;
if (e == foo)
您已经向我们展示了列表类的代码,但这不是错误的原因。该错误是由于缺少操作员entry
类型,无论是什么。要么给班级一个operator==
函数,或声明一个独立的operator==
函数接受一个const entry&
作为它的第一个参数。
struct entry {
bool operator==(const entry& other) const;
};
// or
bool operator==(const entry& lhs, const entry& rhs);
我认为后者是首选风格。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)