读书人

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

发布时间: 2012-03-26 15:46:56 作者: rapoo

大神们 雪地跪求啊 为什么 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;} 

读书人网 >C++

热点推荐