【问题标题】:Error C2955 while implementing a struct/template class based Linked List实现基于结构/模板类的链表时出现错误 C2955
【发布时间】:2020-04-15 16:20:10
【问题描述】:

我正在尝试通过模板类和用于定义节点的结构来实现链接列表。我预计它会编译,但它不会。 Visual Studio 给我的错误是 C2955 “使用类模板需要模板参数列表”并且检查 Microsoft 文档我的代码似乎与任何报告的情况都不匹配。该错误在文件 LinkedList.cpp 的第 15 行报告了两次,其中 add 方法开始。不要看pop函数,因为它没有完全实现。

LinkedList.h 源代码:

#pragma once

template <typename T>

struct TNode {
    T info;
    TNode* next;
    TNode* prev;
};

template <typename T>

class LinkedList {
private:
    TNode* head, * tail;
    int size = 0;
public:
    LinkedList();
    void add(T info);
    T pop();
    T peekTail();
    T peekHead();
    void print();
    void rprint();
    uint64_t length();
    bool empty();
    void debug();
};

LinkedList.cpp 源代码:

#include <cstdlib>
#include <iostream>
#include "LinkedList.h"
using namespace std;

template <typename T>

LinkedList<T>::LinkedList() {
    head = NULL;
    tail = NULL;
}

template <typename T>

void LinkedList<T>::add(T info) {
    TNode* temp = new TNode;
    temp->info = info;
    temp->next = NULL;
    if (head == NULL) {
        head = temp;
        tail = temp;
    }
    else {
        tail->next = temp;
        temp->prev = tail;
        tail = tail->next;
    }
    size++;
}

template <typename T>

T LinkedList<T>::pop() {
    if (size != 0) {
        T info = tail->info;

        size--;
        return info;
    }
}

template <typename T>

T LinkedList<T>::peekTail() {
    return tail->info;
}

template <typename T>

T LinkedList<T>::peekHead() {
    return head->info;
}

template <typename T>

void LinkedList<T>::print() {
    cout << "Elements of the Linked List: ";
    TNode* temp = head;
    while (temp != NULL) {
        cout << temp->info << " ";
        temp = temp->next;
    }
}

template <typename T>

void LinkedList<T>::rprint() {
    cout << "Elements of the Linked List (Reverse): ";
    TNode* temp = tail;
    while (temp != NULL) {
        cout << temp->info << " ";
        temp = temp->prev;
    }
}

template <typename T>

uint64_t LinkedList<T>::length() {
    return size;
}

template <typename T>

bool LinkedList<T>::empty() {
    if (size == 0)
        return true;
    else
        return false;
}

template <typename T>

void LinkedList<T>::debug() {
    cout << length() << endl;
    print();
    cout << endl;
    rprint();
}

我该如何解决这个问题?

【问题讨论】:

  • 为了模板实体可读性的内聚性,请考虑删除模板 id (template-name &lt; parameter-list &gt;) 和随后的类/函数声明之间的空行。
  • @RichardCritten,这最终会成为一个问题,但与 OP 所遇到的错误无关。
  • TNode* temp = new TNode; -> TNode* temp = new TNode&lt;T&gt;;

标签: c++ class templates struct


【解决方案1】:

你有TNode* head, * tail;,但是TNode是一个模板类,所以你必须给它一个类型。在您的情况下,您可能需要TNode&lt;T&gt; *head, *tail;,以便该节点包含与链表相同的内容。 LinkedList 中使用 TNode 的任何地方也需要指定模板参数。

不过,您最终会遇到其他问题。原因见here

【讨论】:

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