模板类的成员函数,采用模板类型作为参数
我有一个节点结构和堆栈类。当我将“void Push(T data)”的定义放在类定义之外时,我得到:
error: 'template<class T> class Stack' used without template parameters
但是当我将其放在类定义内时,它工作正常。
这是代码:
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) 的实现是:
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;
}
编辑:解决方案有效,只是现在每当我尝试调用函数时都会收到链接错误。
Stack<int>::Pop", referenced from
_main in main.o
symbol(s) not found.
除非定义位于 Stack.h 而不是 Stack.cpp 中
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
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;
};
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;
}
Edit: 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.
unless the definitions are in Stack.h instead of Stack.cpp
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要再次使用
模板
(然后再次使用该T
作为该类的模板参数):You need to use the
template <class T>
again (and then use thatT
again as the template parameter for the class):在类外部定义时,需要在成员函数之前添加模板语句...
(至少应该与此类似。)
You need to add a template statement before member functions when defined outside of the class...
(At least it should be similar to this.)
这是因为当定义位于类定义内部时,它知道模板参数。如果你想把定义放在外面,你需要明确地告诉编译器 T 是一个模板参数......
That's because when the definition is inside the class definition it knows the template parameter. If you want to put the definition outside you need to explicitly tell the compiler that T is a template parameter...