我正在尝试实现 C++ 链表,但出现了 6 次此错误。
上线:
error: expected constructor, destructor, or type conversion before '<' token
5,13,19,26,45,
在标题的第 13 行:error: expected unqualified-id before 'template'
你知道为什么吗?
标题:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
// includes
#include <iostream>
#include <stdexcept>
template <typename Type> struct Node
{
Type& data;
struct Node* next;
}
template <typename Type> class LinkedList
{
private:
Node* head;
unsigned length;
public:
LinkedList();
virtual ~LinkedList();
LinkedList(const LinkedList& other);
LinkedList& add(Type& data);
Node& operator[](unsigned index);
friend ostream& operator << (ostream& out, Node& data);
};
#endif // LINKEDLIST_H
资源:
#include "../include/LinkedList.h"
using namespace std;
template <typename Type>
LinkedList<Type>::LinkedList<Type>()
{
head = NULL;
head->next = NULL;
length = 0;
}
template <typename Type>
LinkedList<Type>::~LinkedList<Type>()
{
//dtor
}
template <typename Type>
LinkedList<Type>::LinkedList(const LinkedList& other)
{
//copy ctor
}
template <typename Type>
LinkedList<Type>& LinkedList<Type>::add(Type& data)
{
Node<Type>* ptr = head, *last;
while(ptr)
{
last = ptr;
ptr = ptr->next;
}
// ptr now is null
// try {ptr = new Node<Type>();}
// catch (bad_alloc& e) { cout << "Bad allocation .."; terminate();}
ptr->data = data;
ptr->next = NULL;
last->next = ptr ; // link the previos;
++length;
return *ptr;
}
template <typename Type>
Node<Type>& LinkedList<Type>::operator[] (unsigned index)
{
if(index < 0 || index >= length) throw std::out_of_range("Out of range exception thrown!");
Node<Type>* ptr = head;
for(int i = 0; i < index; ++i) ptr = ptr->next;
return *ptr;
}
template <typename Type>
std::ostream& operator << (std::ostream& out, Node<Type>& data)
{
out << data.data << " ";
return out;
}
你知道这个错误信息是什么意思吗?以及如何解决?
非常感谢。