Связанный шаблон стека и куча ошибок

0

Кто-нибудь скажет мне, что я сделал не так? Если я прокомментирую все утверждения внутри основной функции, компилятор не собирается жаловаться. Итак, я думаю, что это имеет какое-то отношение к основной функции, прямо, когда я создаю новый экземпляр LinkedStack.

LinkedNode.h

#include<memory>

template<class T>
class LinkedNode
{
    friend std::ostream& operator<<(std::ostream& os, const LinkedNode<T>& obj);

    public:
        LinkedNode(T newElement);
        T GetElement() const {return element;}
        void SetElement(T val) {element = val;}
        LinkedNode<T>* GetNext() const {return next;}
        void SetNext(LinkedNode<T>* val) {next = val;}
    private:
        T element;
        LinkedNode<T>* next;
};


template<class T>
LinkedNode<T>::LinkedNode(T newElement)
{
    element = newElement;
}

template<class T>
std::ostream& operator<<(std::ostream& os, const LinkedNode<T>& obj)
{
    os << obj.element << endl;
    return os;
}

LinkedStack.h

#pragma once
#include"LinkedNode.h"
#include<cassert>

template<class T>
class LinkedStack
{
    public:
        LinkedStack();
        int GetSize() const {return size;}
        bool IsEmpty() const {return size == 0;}
        void Push(T val);
        void Pop();
        T Peek();
        void Clear();
    private:
        LinkedNode<T>* head;
        int size;

};


template<class T>
LinkedStack<T>::LinkedStack():size(0) {}

template<class T>
void LinkedStack<T>::Push(T val)
{
    LinkedNode<T>* newOne = new LinkedNode<T>(val);
    if(head == 0)
        head = newOne;
    else
    {
        newOne->next = head;
        head = newOne;
    }
    size++;
}

template<class T>
void LinkedStack<T>::Pop()
{
    assert(!IsEmpty());
    LinkedNode<T>* tpHead = head;
    head = head->next;
    delete tpHead;
    size--;
}

template<class T>
T LinkedStack<T>::Peek()
{
    assert(!IsEmpty());
    return head->element;
}

template<class T>
void LinkedStack<T>::Clear()
{
    while(!IsEmpty())
        Pop();
}

Source.cpp

#include"LinkedStack.h"
#include<iostream>
#include<string>
#include<memory>

int main()
{
    LinkedStack<int> stack;

    std::cout << "Add" << std::endl;
    stack.Push(1);
    stack.Push(2);
    stack.Push(3);
    stack.Push(4);
    stack.Push(5);
    std::cout << "Top element is: " << stack.Peek();
    stack.Pop();
    std::cout << "After pop one out, its top element is: " << stack.Peek() << std::endl;

    return 0;
}

И это все ошибки, которые у меня есть:

    Warning 29  warning C4091: 'typedef ' : ignored on left of '_Collvec' when no variable is declared  c:\program files (x86)\microsoft visual studio 11.0\vc\include\xlocinfo.h   58
Error   4   error C3857: 'LinkedStack': multiple template parameter lists are not allowed   e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    5
Error   3   error C2989: 'LinkedStack' : class template has already been declared as a non-class template   e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    20
Error   26  error C2989: 'lconv' : class template has already been declared as a non-class template c:\program files (x86)\microsoft visual studio 11.0\vc\include\locale.h 82
Error   27  error C2989: 'lconv' : class template has already been declared as a non-class template c:\program files (x86)\microsoft visual studio 11.0\vc\include\locale.h 109
Error   5   error C2988: unrecognizable template declaration/definition e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    23
Error   12  error C2988: unrecognizable template declaration/definition e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    40
Error   21  error C2988: unrecognizable template declaration/definition e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    57
Error   9   error C2447: '{' : missing function header (old-style formal list?) e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    27
Error   17  error C2447: '{' : missing function header (old-style formal list?) e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    51
Error   25  error C2447: '{' : missing function header (old-style formal list?) c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring  13
Error   2   error C2238: unexpected token(s) preceding ';'  e:\fall 2013\cpsc 131\test\linkedstack\linkednode.h 6
Error   11  error C2182: 'LinkedStack' : illegal use of type 'void' e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    40
Error   19  error C2182: 'LinkedStack' : illegal use of type 'void' e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    57
Error   28  error C2143: syntax error : missing ';' before 'identifier' c:\program files (x86)\microsoft visual studio 11.0\vc\include\xlocinfo.h   58
Error   10  error C2143: syntax error : missing ';' before '<'  e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    40
Error   18  error C2143: syntax error : missing ';' before '<'  e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    57
Error   8   error C2143: syntax error : missing ';' before '{'  e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    27
Error   16  error C2143: syntax error : missing ';' before '{'  e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    51
Error   24  error C2143: syntax error : missing ';' before '{'  c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring  13
Error   20  error C2086: 'int LinkedStack' : redefinition   e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    57
Error   1   error C2059: syntax error : '<' e:\fall 2013\cpsc 131\test\linkedstack\linkednode.h 6
Error   6   error C2059: syntax error : '<' e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    23
Error   13  error C2059: syntax error : '<' e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    40
Error   22  error C2059: syntax error : '<' e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    57
Error   7   error C2039: 'Push' : is not a member of ''global namespace''   e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    26
Error   14  error C2039: 'Pop' : is not a member of ''global namespace''    e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    40
Error   15  error C2039: 'Peek' : is not a member of ''global namespace''   e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    50
Error   23  error C2039: 'Clear' : is not a member of ''global namespace''  e:\fall 2013\cpsc 131\test\linkedstack\linkedstack.h    57
Error   30  error C1075: end of file found before the left brace '{' at 'c:\program files (x86)\microsoft visual studio 11.0\vc\include\xlocinfo.h(18)' was matched c:\program files (x86)\microsoft visual studio 11.0\vc\include\xlocinfo.h   58
Теги:
stack

1 ответ

2

Ошибка в ваших файлах заголовков. Причина, по которой вы не видите ошибку компилятора при комментировании своей main функции, связана с тем, как работают шаблоны (они в основном являются основой для создания объекта, но определение фактически не создается до тех пор, пока вы не попытаетесь создать его экземпляр).

Похоже, что у вас отсутствует защита заголовка в файле LinkedNode.h. Поместите #pragma once наверху (или используйте # ifndef/# define). Но я не думаю, что это причина ваших ошибок.

По-видимому, вы объявили не-шаблонную версию LinkedStack или потенциально имеете следующий синтаксис где-то (который вы не показывали):

template<class T>
template<class N>
class LinkedStack {... }

Для классов шаблонов это небольшое, я бы рекомендовал написать их inline, поскольку это обычно делает вашу ошибку легче заметить.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню