我试图为堆栈实现模板,但编译时出错。
这是我的Stack.h
文件
const int MAX_STACK = 2;
enum STATE { OK = 0, STACK_FULL, STACK_EMPTY };
template <class T>
class Stack
{
public:
Stack();
void Clear();
int Push(T x);
int Pop(T * w);
int StackState();
private:
T t[MAX_STACK];
int top;
};
和我的Stack.cpp
文件
#include "Stack.h"
template<class T>
Stack<T>::Stack():
top(0) {}
template<class T>
void Stack<T>::Clear()
{
top = 0;
}
template<class T>
int Stack<T>::Push(T x)
{
if (top < MAX_STACK)
{
t[top++] = x;
return OK;
}
else
{
return STACK_FULL;
}
}
template<class T>
int Stack<T>::Pop(T * w)
{
if (top > 0)
{
*w = t[--top];
return OK;
}
else
{
return STACK_EMPTY;
}
}
template<class T>
int Stack<T>::StackState()
{
switch (top)
{
case 0:
return STACK_EMPTY;
case MAX_STACK:
return STACK_FULL;
default:
return OK;
}
}
Main.cpp
#include <iostream>
#include "Stack.h"
int main()
{
Stack<char *> stack;
char tab[3] = { 'V', 'E', 'R' };
std::cout << "Inserting into stack:\n";
for (int i = 0; i < 3; i++)
{
if (stack.StackState() != STACK_FULL)
{
std::cout << "Trying to insert " << tab[i] << ",\n";
stack.Push(&tab[i]);
}
else
{
std::cout << "Stack is full!\n";
break;
}
}
std::cout << "\n\nDeleting items from stack: ";
for (int i = 0; i < 3; i++)
{
char ** z;
if (stack.Pop(z) == OK)
{
std::cout << "Deletion successful: " << **z << "\n";
}
}
return 0;
}
但是收到此错误
Undefined symbols for architecture x86_64:
"Stack<char*>::StackState()", referenced from:
_main in main.o
"Stack<char*>::Pop(char**)", referenced from:
_main in main.o
"Stack<char*>::Push(char*)", referenced from:
_main in main.o
"Stack<char*>::Stack()", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
感谢你的想法。