【问题标题】:C++ Use of template class LinkedList requires template argumentsC++ 使用模板类 LinkedList 需要模板参数
【发布时间】:2013-10-19 18:54:09
【问题描述】:

因此,当我的 Linked List 类仅使用 ints 而不是模板 T 时,它工作得很好,但是当我经历并更改所有要模板化的内容时,它给了我和错误说“使用模板类 LinkedList 需要模板参数” .

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

#include <iostream>
#include <memory>

template<typename T>
class LinkedList
{
private:

    struct Node
    {
        T data;
        std::shared_ptr<Node> next;

        Node(T d, std::shared_ptr<Node> n)
        :data(d)
        ,next(n)
        {}
        Node()
        {};

        T getData()
        {
            return data;
        }

    };


    std::shared_ptr<Node> head;
    std::shared_ptr<Node> current;


public:


    LinkedList()
    :head()
    {}
    LinkedList(LinkedList& other)
    :head(Clone(other.head))
    {}

^This is where I think the problem is but did I just forget to replace an int somewhere?  I've looked this over a lot and I haven't found anything but I could just be blind.  

    std::shared_ptr<Node> getStart() const
    {
        return head;
    }

    //Insertion
    void InsertAt(T value, std::shared_ptr<Node> &n)
    {
        n = std::make_shared<Node>(value, n);

    }

    void Insertion(T value)
    {
        Insertion(value, head);
    }

    void Insertion(T value, std::shared_ptr<Node> &n)
    {
        if (!n)
        {
            InsertAt(value, n);
            return;
        }

        if (value > n->data)
            Insertion(value, n->next);
        else
            InsertAt(value, n);

    }

    //Deletion
    void Remove(T value)
    {
        Remove(value, head);
    }

    void Remove(T value, std::shared_ptr<Node>& n)
    {
        if (!n) return;
        if (n->data == value)
        {
            n = n->next;
            Remove(value, n);
        }
        else
        {
            Remove(value, n->next);
        }
    }



    void for_each(const std::shared_ptr<Node> &n)
    {
        if(!n) return;

        else
        {
            std::cout<<n->data<<std::endl;
            for_each(n->next);
        }

    }



    std::shared_ptr<Node> Clone(std::shared_ptr<Node> n) const
    {
        if(!n) return nullptr;
        return std::make_shared<Node>(n->data, Clone(n->next));
    }

    LinkedList& operator = (const LinkedList &list)
    {
        head = list.head;
        this->Clone(head);
        return *this;
    }



};



#endif

【问题讨论】:

  • 我使用g++ -c -std=c++11 q.cpp (g++ ver. 4.8.1) 编译了你的代码,没有错误
  • 您能否展示您使用此类模板的代码部分(因为我认为这是您的错误发生的地方。您是否在实例化时明确指定了类型?)
  • 该错误表示您在实例化模板时没有指定模板参数。在上面的代码中没有模板实例化。
  • 请提供LinkedList 模板实例化的示例。上面的代码看起来是正确的。好像您忘记在实例化过程中指定类型参数。

标签: c++ templates linked-list nodes


【解决方案1】:

您是否也更改了使用LinkedList 的代码?

例如整数链表:LinkedList&lt;int&gt; list;

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多