模板类的成员函数,将模板类型作为参数 [英] Member functions of a templated class, that take a template type as argument
问题描述
我有一个节点结构和堆栈类。当我把'void Push(T data)'的定义放在类定义之外时,我得到:
I have a node struct and stack class. When I put the definition for 'void Push(T data)' outside the class definition I get:
error: 'template<class T> class Stack' used without template parameters
但是当我把它放在类定义里面它工作正常。 br>
下面是代码:
But when I put it inside the class definition it works fine.
Here is the code:
template <class T>
struct Node
{
Node(T data, Node <T> * address) : Data(data), p_Next(address) {}
T Data;
Node <T> * p_Next;
};
template <class T>
class Stack
{
public:
Stack() : size(0) {}
void Push(T data);
T Pop();
private:
int size;
Node <T> * p_first;
Node <T> * p_last;
};
Push(T data)的实现是:
The implementation for Push(T data) is :
void Stack::Push(T data)
{
Node <T> * newNode;
if(size==0)
newNode = new Node <T> (data, NULL);
else
newNode = new Node <T> (data, p_last);
size++;
p_last = newNode;
}
编辑:解决方案工作除了现在我得到一个链接错误,调用函数。
The solutions worked except that now I get a linking error whenever I try to call the functions.
Stack<int>::Pop", referenced from
_main in main.o
symbol(s) not found.
除非Stack.h中的定义是Stack.cpp
unless the definitions are in Stack.h instead of Stack.cpp
推荐答案
您需要再次使用模板< class T>
再次使用 T
作为类的模板参数):
You need to use the template <class T>
again (and then use that T
again as the template parameter for the class):
template <class T>
void Stack<T>::Push(T data)
{
Node <T> * newNode;
if(size==0)
newNode = new Node <T> (data, NULL);
else
newNode = new Node <T> (data, p_last);
size++;
p_last = newNode;
}
这篇关于模板类的成员函数,将模板类型作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!