首页 文章

在c中的模板中使用运算符

提问于
浏览
1

我正在尝试使用指针实现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>&'from'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;

5 回答

  • 1

    开始删除代码,直到它再次工作 . 一些拼写错误或流氓宏或冲突的命名空间搞砸了 .

    这会自行编译吗?

    string data = "bla";
    Node<string> p("bla");
    bool b = p.data() == data;
    

    (每个C程序员都应该制作一个cout <<“bla”<< end; typo . 非常有趣)

  • 4

    试试:

    if( n.compare(p->data()) == 0 )
    

    string::compare documentation

    正如下面的评论所指出的那样,operator ==应该可行 . 请仔细检查一下

    #include <string>
    using std::string;
    
  • 0

    在没有深入研究代码的情况下,我注意到了一些问题 .

    首先,

    locate(T n)
    

    应该

    locate(const T& n)
    

    这节省了n的可能副本

    问一个愚蠢的问题,你确定你做过:

    #include <string>
    
  • 0

    std::istreambuf_iterator 的引用很奇怪,因为你所展示的代码中没有任何内容证明它是正确的 - 你可以告诉我们 Node 以及其他任何代码在最小的失败示例中对此产生影响吗?试图从非常局部的代码和错误信息中解决问题非常像拔牙......! - )

  • 0

    这看起来不错,我看不出 std::istreambuf_iterator 如何进入图片......

    您可能想要调整的一件事是将 const T& 而不是 T 作为参数添加到您的方法中,例如

    Node(const T& d, Node<T> * l = NULL);
      void data(const T& d);
    
      int List<T>::locate(const T& n) const { ...
    

    实际问题是什么,必然会有其他事情发生 .

相关问题