Мне нужна помощь в создании шаблона стека c ++. Ошибка "StackType <int>:: ~ StackType <int>(void)"? - PullRequest
0 голосов
/ 03 апреля 2011

Я новичок в программировании, в нашем курсе c ++ мы должны построить класс стека и использовать шаблон, я следовал книге и пытался собрать ее вместе, но все еще много ошибок. Поэтому я надеюсь, что эксперты здесь помогут указать мне правильное направление.

StackType.h

class FullStack
{};

class EmptyStack
{};

template<class ItemType>
class StackType
{
    public:
    StackType(int max);
    /*
     * Function: constructor
     * Precondition: none
     * Postcondition: Stack has been initialized
     */

    bool IsEmpty() const;
    /*
     * Function: Determines whether the stack is empty
     * Precondition: Stack has been initialized
     * Postcondition: Function value = (stack is empty)
     */

    bool IsFull() const;
    /*
     * Function: Determines whether the stack is full
     * Precondition: Stack has been initialized
     * Postcondition: Function value = (stack is full)
     */

    void Push(ItemType item);
    /*
     * Function: Add new item to the top of the stack
     * Precondition: Stack has been initialized
     * Postcondition: If (stack is full), exception FullStack is thrown,
     *                else new item is at the top of the stack
     */

    void Pop();
    /*
     * Function: Remove top item from the stack
     * Precondition: Stack has been initialized
     * Postcondition: If (stack is empty), exception EmptyStack is thrown,
     *                else top item has been removed from stack
     */

    ItemType Top() const;
    /*
     * Function: Returns value of the top item from the stack
     * Precondition: Stack has been initialized
     * Postcondition: If (stack is empty), exception EmptyStack is thrown,
     *                else value of the top item is returned
     */

    ~StackType(void);
    /*
     * Function: destructor
     * Precondition: Stack has been initailized
     * Postcondition: deallocate memory
     */

private:
    int maxStack;
    ItemType* item;
    int top;
};

StackType.cpp

#include "StackType.h"
#include <iostream>
#include <string>
using namespace std;

template<class ItemType>
StackType<ItemType>::StackType(int max)
{
    maxStack = max;
    top = -1;
    item = new ItemType[maxStack];
}

template<class ItemType>
bool StackType<ItemType>::IsEmpty() const
{
    return (top == -1);
}

template<class ItemType>
bool StackType<ItemType>::IsFull() const
{
    return (top == maxStack - 1);
}

template<class ItemType>
void StackType<ItemType>::Push(ItemType newItem)
{
    if(IsFull())
        throw FullStack();
    top++;
    item[top] = newItem;
}

template<class ItemType>
void StackType<ItemType>::Pop()
{
    if(IsEmpty())
        throw EmptyStack();
    top--;
}

template<class ItemType>
ItemType StackType<ItemType>::Top() const
{
    if(IsEmpty())
        throw EmptyStack();
    return item[top];
}

template<class ItemType>
StackType<ItemType>::~StackType()
{
    delete []item;
}

Спасибо всем в продвинутом:)

Обновление: Похоже, класс построен, и все в порядке. Но когда я строю код клиента для его тестирования, я получаю следующие ошибки:

1> client_code.obj: ошибка LNK2019: неразрешенный внешний символ "public: __thiscall StackType :: ~ StackType (void)" (?? 1? $ StackType @ H @@ QAE @ XZ), на который есть ссылка в функции _main

1> client_code.obj: ошибка LNK2019: неразрешенный внешний символ "public: void __thiscall StackType :: Push (int)" (? Push @? $ StackType @ H @@ QAEXH @ Z), на который есть ссылка в функции _main

1> client_code.obj: ошибка LNK2019: неразрешенный внешний символ "public: __thiscall StackType :: StackType (int)" (?? 0? $ StackType @ H @@ QAE @ H @ Z), на который есть ссылка в функции _main

1> C: \ Users \ Alakazaam \ Desktop \ Stack \ Debug \ Stack.exe: фатальная ошибка LNK1120: 3 неразрешенных внешних кода

main.cpp

#include <iostream>
#include <string>
#include "StackType.h"
using namespace std;


int main()
{

    int num;
    StackType<int> stack(4);

    for(int i = 0; i < 4; i++)
    {
        cin >> num;
        stack.Push(num);
    }

    return 0;
}

Обновление:

Я получил решение, что StackType.h и StackType.cpp должны находиться в одном и том же заголовочном файле StackType.h (StackType.cpp не нужен, поскольку я использую Template. Поэтому все, что должно быть в StackType.cpp, просто перейдите в конец StackType.h)

Спасибо всем за помощь:)

Ответы [ 2 ]

2 голосов
/ 03 апреля 2011

Изменить это:

template <class ItemType>

class FullStack
{};

class EmptyStack
{};

class StackType

Должно быть:

class FullStack
{};

class EmptyStack
{};

template <class ItemType>
class StackType
// This tells the compiler StackType is a template that uses ItemType internally.

Примечание 1: использование class ItemType является правильным, но поскольку ItemType может быть не типом класса, я предпочитаю использовать форму typename:

template<typename ItemType>
class StackType

Примечание 2. Из-за особенностей работы шаблонов. Обычно лучше всего поместить определение метода в заголовочный файл (вместе с классом). Он может работать с файлом cpp, но требует дополнительной работы. Самое простое решение для вас:

  1. Переименование «StackType.cpp» в «StackType.tpp»
  2. Добавить "#include " в конец "StackType.h"

Примечание 3: using namespace std; - это плохая практика (все книги делают это, чтобы сэкономить место в долгосрочной перспективе, и вам будет лучше, не слишком). Нетрудно добавить префикс std к std::

0 голосов
/ 03 апреля 2011

Вы должны поставить этот код на http://codereview.stackexchange.com.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...