好的,所以我正在尝试在 C++ 中实现一个模板化的循环双向链表。我遇到的问题是,当我尝试将类定义和函数分别分离到 .h 和 .cpp 文件中时,编译器不断向我吐出关于没有模板参数的错误。
这里是头文件,cdl_list.h
#ifndef CDL_LIST_H
#define CDL_LIST_H
#include <iostream>
using namespace std;
template <typename T>
class cdl_list {
public:
cdl_list(){
first = last = current = NULL;}; // constructor, "current" = "null"
~cdl_list(); // deconstructor
void insertFromFront (T &); // inserts an element of type T in the front properly
void insertFromBack (T &); // inserts an element of type T in the back properly
void deleteFront(); // removes the first element in the list, updating relevant pointers
void deleteBack(); // removes the last element in the list, updating relevant pointers
void reset(); // makes the "current" pointer the front element
void next(); // makes the "current" pointer the next node neighbor
T currentValue(); // return the data in the node that "current" refers to
void deleteCurrent(); // delete the node that the current pointer refers to; current = old -> next
bool isEmpty(); // returns true if and only if the list is empty
void print(); // displays the current data in the linked list
private:
struct listNode* first;
struct listNode* last;
struct listNode* current;
protected:
struct listNode {
listNode* prev; // "previous" pointer
T data; // data in the node
listNode* next; // "next" pointer
};
};
#include "cdl_list.h"
#include <iostream>
using namespace std;
//And here is the .cpp file, what I have so far, because I can't even get just this one function to compile
template < typename T > void cdl_list::insertFromFront(const T &frontInsert) {
listNode *oldFirst;
oldFirst = (listNode *) malloc(sizeof(listNode));
oldFirst = first;
oldFirst -> prev = frontInsert;
while(current -> next != first)
current = current -> next;
frontInsert -> prev = current;
current -> next = frontInsert;
first = frontInsert;
}
#endif
最佳答案
不幸的是,由于 C++ 编译过程的工作方式,它们需要在同一个文件中(除此之外还有其他解决方法,但这是最常见的一种)。参见 http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12了解更多详情。
关于c++ - 在 C++ 中创建新的模板容器类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5189153/