我想实现一个使用指针的List类,并试图实现一个函数LOCATE(T x)其中T代表模板并返回元素x的第一个位置(如果找到),否则返回最后一个位置+ 1在C++模板中使用运算符
我的功能代码是
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;
,但我得到一个错误信息
'布尔的std ::运算符==(常量的std :: istreambuf_iterator < _Elem,_Traits> &,常量的std :: istreambuf_iterator < _Elem,_Traits> &)':不能推导出模板参数的“常量性病:: istreambuf_iterator < _Elem,_Traits> &'from'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;
你可以发表节点的代码? – rlbond 2009-07-17 05:27:46
你对节点的定义是什么样的?而完整的调用代码,以“列表 myList;”开头的代码,如上所示? 谢谢。 –
2009-07-17 05:30:46
刚刚发布节点的定义和调用代码 –
Jaelebi
2009-07-17 05:35:01