我正在尝试使用指针实现一个 List 类,并尝试实现一个函数 LOCATE(T x),其中 T 用于模板,如果找到则返回元素 x 的第一个位置,否则返回最后一个位置 + 1。
我的功能代码是
template<class T>
int List<T>::locate(T n) const
{
int size = end();
Node<T> * p = head_;
for (int i = 0; i < size; i++)
{
if (p->data() == n) // fails on this line
return i;
p = p->link();
}
return size; // if no match found
}
我用 T 作为字符串初始化我的列表
List<string> myList;
但我收到一条错误消息
'bool std::operator ==(const std::istreambuf_iterator<_Elem,_Traits> &,const std::istreambuf_iterator<_Elem,_Traits> &)' : 无法推导出 'const std::istreambuf_iterator<_Elem 的模板参数, _Traits> &' 来自 'std::string
即使为字符串类定义了“==”运算符,为什么还会出现错误?'
节点的代码是
template<typename T>
class Node
{
public:
// Constructors
Node();
Node(T d, Node<T> * l = NULL);
//Inspectors
T data() const;
Node<T> * link() const;
// Mutators
void data(T d); // assigns new value to Node
void link(Node<T> * l); // points this Node to a different one
// Destructor
~Node();
private:
Node<T> * link_;
T data_;
};
template<typename T>
T Node<T>::data() const
{
return data_;
}
template<typename T>
Node<T>* Node<T>::link() const
{
return link_;
}
调用代码是
List<string> test;
test.add("abc");
cout << test.locate("abc") << endl;