【发布时间】: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 < parameter-list >) 和随后的类/函数声明之间的空行。 -
@RichardCritten,这最终会成为一个问题,但与 OP 所遇到的错误无关。
-
TNode* temp = new TNode;->TNode* temp = new TNode<T>;
标签: c++ class templates struct