您的位置:程序门 -> c/c++ -> c++ 语言



为什么不能输出?


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


为什么不能输出?
发表于:2008-01-10 09:17:50 楼主
我在stack.h头文件定义了栈如下,
#ifndef   stack_h
#define   stack_h

template <class   t>
class   stack
{
public:
stack(int   stacksize=100);
~stack();
bool   gettop(t&   e);  
bool   pop(t&   e);      
bool   push(t   e);
bool   empty();
int   stackelem();
private:
t   *base;   //栈底指针
t   *top;     //栈顶指针
int   size;
};

template <class   t>   stack <t> ::stack(int   stacksize=100)
{
        if(stacksize <=0)exit(1);
base=new   t(stacksize);
if(!base)exit(1);
top=base;
size=stacksize;
}

template <class   t>   stack <t> ::~stack()
{
if(base)delete[]   base;
}

template <class   t>   bool   stack <t> ::gettop(t&   e)
{
if(base==top)
{
//栈为空
return   false;
}
else
{
e=*(top-1);
return   true;
}
}

template <class   t>   bool   stack <t> ::pop(t   &e)
{
if(base==top)
{
//栈为空
return   false;
}
else
{
e=*(--top);
return   true;
}
}

template <class   t>   bool   stack <t> ::push(t   e)
{
if(top-base> =size)
{
//栈已满
return   false;
}
else
{
*top++=e;
return   true;
}
}

template <class   t>   bool   stack <t> ::empty()
{
return   (base==top);
}

template <class   t>   int   stack <t> ::stackelem()
{
return   top-base;
}

#endif

然后包含这一头文件,实现栈的操作,但是出栈后输出元素会出现运行错误,是什么原因啊?
#include   "stdafx.h"
#include <iostream>
#include"stack.h"
using   namespace   std;

int   _tmain(int   argc,   _tchar*   argv[])
{
stack <int>   *ps=new   stack <int> (200);
for(int   k=0;k <20;k++)
ps-> push(k);
int   temp;
while(!ps-> empty())
{
if(ps-> pop(temp))cout < <temp < <endl;

}
system("pause");
return   0;
}

发表于:2008-01-10 09:38:431楼 得分:0
base=new     t(stacksize);   //这只创建了一个对象
正确的应该是:
base   =   new   t[stacksize];
发表于:2008-01-10 09:56:312楼 得分:0
栈指针出错,构造函数应该是

c/c++ code
template <class t> stack <t>::stack(int stacksize = 100) : base(null) { if(stacksize <=0) exit(1); base = new t[stacksize]; // 改成这样 if!base) exit(1); top = base; size = stacksize; }
发表于:2008-01-10 09:59:333楼 得分:0
喔,明白了,谢谢


快速检索

最新资讯
热门点击