首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

大神们 雪地跪求啊 为什么 pop的返回值错误

2012-03-26 
大神们 雪地跪求啊为什么 pop的返回值异常啊#includeiostreamusing namespace stdtemplate class Tcl

大神们 雪地跪求啊 为什么 pop的返回值异常啊
#include<iostream>
using namespace std;
template <class T>
class stack
{ private:
  T a[10];
  int nuMber;
 public:
  void push(T meMber)
  {
  if(full())
  throw "the stack is full";
  a[nuMber++]=meMber;
  }
  T pop()
  { 
  if(empty())
  throw 100;
  T meMber=a[nuMber--];
  return meMber;
  }
  bool full()
  {
  return (nuMber==9);
   
  }
  bool empty()
  {
  return (nuMber==0);
  }
  int size()
  {
  return nuMber;
  }
  int capacity()
  {
  return 10;
  }
  void clear()
  {
  nuMber=0;
  }
  stack()
  {
  nuMber=0;
  }
};
int main()
{
  stack<int> a;
  a.push(10);
  cout<<a.size()<<endl;
  cout<<a.pop()<<endl;
  cout<<a.size()<<endl;
  a.push(10);
  cout<<a.pop()<<endl;
  return 0;
}
返回值

1
32657
0
32657


[解决办法]
见注释 ~

C/C++ code
#include<iostream>using namespace std;template <class T>class stack{ private:    T a[10];    int nuMber;public:    void push(T meMber)    {        if(full())            throw "the stack is full";        a[nuMber++]=meMber;              //stack 采用默认构造函数 nuMber值初始化为0                                        //此处 a[0] = meMber                                        //nuMber自加 nuMber = 1    }    T pop()    {          if(empty())            throw 100;        T meMber=a[nuMber--];           //meMber = a[1];(此处a[1]没有初始化,返回值不确定)                                        //nuMber 自减 nuMber = 0;        return meMber;                        }    bool full()    {        return (nuMber==9);    }    bool empty()    {        return (nuMber==0);    }    int size()    {        return nuMber;    }    int capacity()    {        return 10;    }    void clear()    {        nuMber=0;    }    stack()    {        nuMber=0;    }};int main(){    stack<int> a;    a.push(10);    cout<<a.size()<<endl;    cout<<a.pop()<<endl;    cout<<a.size()<<endl;    a.push(10);    cout<<a.pop()<<endl;    system("pause");    return 0;} 

热点排行