【问题标题】:How to fix this error in my c++ linked list code, "LL is not a template"?如何修复我的 C++ 链表代码中的这个错误,\"LL is not a template\"?
【发布时间】:2022-12-17 18:39:59
【问题描述】:

这是我用一些操作创建了一个基本链表的代码,但无法使用模板类型。 说 LL 不是模板。


template <typename T>                         //typename 
class node
{
public:
    T data;                                  //type T
    node *next;
};
class LL
{
    node *head = NULL;

public:
    void insert(auto val)
    {
        node *n = new node;
        n->data = val;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            return;
        }
        else
        {
            node *temp = head;                    //head not declared error though I declared it 
            while (temp->next != NULL)
            {
                temp = temp->next;
            }
            temp->next = n;
            return;
        }
    }
    void display()
    {
        node *temp = head;                        //head not declared error though I declared it 
        while (temp != NULL)
        {
            cout << temp->data << "->";
            temp = temp->next;
        }
        cout << "NULL" << endl;
        return;
    }
};
int main()
{
    LL<int> obj;                     //its correctly defined
    obj.insert(1);
    obj.insert(3);
    obj.display();
    return 0;
}

它还会给出更多错误,如上面代码中所评论的那样。(所有与模板相关)。

【问题讨论】:

  • node 是一个模板。 LL 不是。
  • 那我应该改变什么?
  • 先把LL改成模板。然后使用 LL 及其成员函数中的 node 指针的模板参数。

标签: c++ templates linked-list


【解决方案1】:

而不是这个:

class LL
{
    node *head = NULL;

public:
    void insert(auto val)
    {
        node *n = new node;

这个:

template <typename T>
class LL
{
    node<T> *head = NULL;

public:
    void insert(T val) 
    {
        node<T> *n = new node<T>;

您需要对 display 函数中的节点声明进行类似的声明更改。

最好将您的 insert 函数真正声明为:

void insert(const T& val) 

因此,您的类可以支持大型对象作为模板类型,而无需制作冗余副本。

【讨论】:

  • 这只是修复的一半。代码还必须用 node&lt;T&gt; 替换 LL 中所有对 node 的使用,或者声明类似 using node_type = node&lt;T&gt;; 的内容并使用 node_type 而不是 node
  • @cptFracassa - 我刚刚在一秒钟前修复了它。
猜你喜欢
  • 2019-09-25
  • 2020-02-09
  • 2022-12-29
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
相关资源
最近更新 更多