我正在尝试使用指针实现一个 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
即使为字符串类定义了“==”运算符,为什么还会出现错误? '
Node的代码是
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;
最佳答案
虽然没有深入研究您的代码,但我发现了几个问题。
首先,
locate(T n)
应该是
locate(const T& n)
这保存了 n 的可能拷贝
然后问一个愚蠢的问题,你确定你已经完成了吗:
#include <string>
关于c++ - 在 C++ 模板中使用运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1141514/