在stack.h中,我有兩個結構Stack和StackElement。在StackElement中,我有一個指向下一個和一個值的指針。所以,我想,我的價值可能是所有類型,例如字符堆棧,雙打堆棧等等。所以,我使用了模板,但有一個錯誤「使用類模板'StackElement'需要模板參數」 。下面是代碼:結構中模板的問題
#pragma once
template <typename T>
struct StackElement
{
T value;
StackElement *next;
};
struct Stack
{
StackElement *top;
};
Stack *createStack();
void push(Stack *stack, char value);
char pop(Stack *stack);
void deleteStack(Stack *stack);
bool isEmpty(Stack *stack);
char check(Stack *stack);
此外,在所有的功能上面我都同樣的錯誤,在這裏StackElement的價值:
#include "stack.h"
template <typename T>
StackElement *createStackElement(T value, StackElement *next)
{
StackElement *newStackElement = new StackElement;
newStackElement->next = next;
newStackElement->value = value;
return newStackElement;
}
Stack *createStack()
{
Stack *newStack = new Stack;
newStack->top = createStackElement(0, nullptr);
return newStack;
}
void push(Stack *stack, T value)
{
StackElement *newElement = createStackElement(value, stack->top->next);
stack->top->next = newElement;
}
char check(Stack *stack)
{
return stack->top->next->value;
}
char pop(Stack *stack)
{
char result = stack->top->next->value;
StackElement *element = stack->top->next;
stack->top->next = stack->top->next->next;
delete element;
return result;
}
bool isEmpty(Stack *stack)
{
return stack->top->next == nullptr;
}
void deleteStack(Stack *stack)
{
while (!isEmpty(stack))
pop(stack);
delete stack->top;
delete stack;
}
請幫我弄清楚,其中的錯誤是。 在此先感謝。
請發佈一個MCVE。大部分代碼與問題無關。 – juanchopanza 2014-10-20 08:17:35