C ++模板错误:在'<'之前的预期构造函数,析构函数或类型转换代币

时间:2012-10-08 10:14:19

标签: c++ templates g++

我正在尝试实现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;
}

您知道此错误消息的含义吗?以及如何解决它?

非常感谢。

1 个答案:

答案 0 :(得分:4)

看起来你需要添加几个&#39 ;;&#39;到你的声明结束。

template <typename Type> struct Node
{
    Type& data;
    struct Node* next;
}; // <<<