C ++模板类错误与operator == [英] C++ template class error with operator ==
问题描述
错误:
错误C2678:binary'==':无操作符,它接受类型为const entry的左侧操作数(或没有可接受的转换)
Error:
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const entry' (or there is no acceptable conversion)
函数:
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;
}
这假设是一个重载运算符?作为模板类我不知道我是否理解错误?
Is this suppose to be an overloaded operator? Being a template class I am not sure I understand the error?
解决方案 -
类中的重载函数现在声明了const:
Solution- The overload function in the class now declared const:
//Operators
bool entry::operator == (const entry& dE) const <--
{
return (name ==dE.name);
}
推荐答案
正确地读取错误文本:
二进制'==':无操作符找到一个左手操作数类型' const entry'
binary '==' : no operator found which takes a left-hand operand of type 'const entry'
这意味着它找不到任何 ==
接受条目
类型作为其左操作数。此代码无效:
It means it can't find any ==
operator that accepts an entry
type as its left operand. This code isn't valid:
entry const e;
if (e == foo)
类,但这不是错误是什么。错误是关于条目
类型缺乏运算符,无论是什么。或者给类一个运算符==
函数,或者声明一个独立的运算符==
函数,接受 const entry&
作为其第一个参数。
You've showed us the code for your list class, but that's not what the error is about. The error is about a lack of operators for the entry
type, whatever that is. Either give the class an operator==
function, or declare a standalone operator==
function that accepts a const entry&
as its first parameter.
struct entry {
bool operator==(const entry& other) const;
};
// or
bool operator==(const entry& lhs, const entry& rhs);
我认为后者是首选风格。
I think the latter is the preferred style.
这篇关于C ++模板类错误与operator ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!