栈的找错

来源:百度知道 编辑:UC知道 时间:2024/09/21 19:03:11
template<class elem>
struct listnode
{
elem data;
listnode<elem>* link;
};

template <class elem>
typedef listnode<elem>* pr;

#include <assert.h>

template<class elem>
class Stack
{
private:
listnode<elem>* top;
public:
Stack(){top=NULL;};
void Push(elem item);
elem Pop();
bool Isempty(){return top==NULL;};
};

template<class elem>
void Stack<elem>::Push(elem item)
{
pr temp=new listnode<elem>;
temp->link=top;
temp->data=item;
top=temp;
}

template <class elem>
elem Stack<elem>::Pop()
{
assert(!Isempty());
pr temp=top;
elem result=top->data;
top=top->link;
delete temp;
return result;
}
不知道错哪了?
error C2440: 'initializing' : cannot convert from 'struct listnod

typedef的最后结果只能是一种类型
而模板是根据使用者的调用会编译成多份不同类型的代码,也就是说,在试图typedef的时候,模板的实际类型还未全部生成(编译器不确定在typedef后是否还有其他类型的模板特化代码生成),所以不可能对模板typedef
这是我的理解
而这样的代码没问题
typedef listnode<int> *ptr;
因为编译器读取到这里只会把一种固定类型映射到另一种类型

另外一个错误是NULL未声明

#define NULL 0

template<class elem>
struct listnode
{
elem data;
listnode<elem> *link;
};

#include <assert.h>

template<class elem>
class Stack
{
private:
listnode<elem>* top;
public:
Stack(){top=NULL;}
void Push(elem item);
elem Pop();
bool Isempty(){return top==NULL;}
};

template<class elem>
void Stack<elem>::Push(elem item)
{
listnode<elem> *temp=new listnode<elem>;
temp->link=top;
temp->data=item;
top=temp;
}

template <class elem>
elem Stack<elem>::Pop()