大家来帮帮小弟我,栈的有关问题
大家来帮帮我,栈的问题
刚才写的代码,用静态数组实现的栈, 写的比较简单, 有错误。。直接上代码,注释里写了
------解决思路----------------------
1楼的说法不准确。
getLength不是const。如果otherS是const,那么就不允许调用otherS.getLength()
要改成
int getLength ( ) const;
刚才写的代码,用静态数组实现的栈, 写的比较简单, 有错误。。直接上代码,注释里写了
#ifndef STACK_H_
#define STACK_H_
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef unsigned int Item;
class Stack
{
private:
enum {MAX=10};
Item items[MAX];
int top;
public:
Stack();
bool isempty() const;
bool isfull() const;
bool push( const Item & item );
bool pop(Item & item );
int getLength ( );
void getTop ( int & e );
friend Stack Randcreat();
Stack( Stack& otherS );
friend void Display ( Stack& A );
Stack operator = ( Stack & Rights );
};
int main()
{
Stack pg;
unsigned int a,b,c;
Stack gp = Randcreat();
Display(gp); //程序运行时不显示,help
pg.push(1);
pg.push(2);
pg.push(3);
int d=pg.getLength();
cout<<"栈的长度为:"<<d;
cout<<endl;
int f;
pg.getTop ( f );
cout<<"栈顶元素为:"<<f<<endl;
cout<<"出栈:";
pg.pop(a);
pg.pop(b);
pg.pop(c);
cout<<a<<b<<c<<endl;
cout<<pg.isempty();
int e=pg.getLength();
cout<<"栈的长度为:"<<e;
system("pause");
return 0;
}
Stack::Stack()
{
top = 0;
}
bool Stack:: isempty() const
{
return top==0;
}
bool Stack:: isfull() const
{
return top==MAX;
}
bool Stack:: push(const Item& item)
{
if(isfull())
return false;
else
{
items[top++]=item;
return true;
}
}
bool Stack :: pop (Item& item )
{
if(isempty())
return false;
else
{
item= items[--top];
return true;
}
}
int Stack :: getLength ()
{
return top;
}
void Stack :: getTop ( int & e )
{
e = items [top-1];
}
Stack Randcreat ()
{
Stack pp;
int n = rand() % 10+1;
for(int i=0; i<n; i++ )
{
int k =rand () % 50 + 1;
pp.push(k);
}
return pp;
}
Stack::Stack( Stack & otherS ) //这里拷贝构造函数, 参数我加上const 就不行, 里面的判段语句我也删了不然会报错
{
for(int i=0; i<otherS.getLength(); i++ )
items[i]=otherS.items[i];
}
void Display( Stack & A ) //这里加了const 也会报错
{
for( int i=0; i<A.getLength() ; i++ )
{
cout<<i+1<<" ";
}
cout<<endl;
for( int j=0; j<A.getLength(); j++ )
{
cout<<A.items[j]<<" ";
}
cout<<endl;
}
Stack Stack:: operator = ( Stack & Rights )
{
if( this != & Rights )
{
for( int i=0; i<Rights.getLength(); i++ )
items[i]=Rights.items[i];
}
return *this;
}
#endif
------解决思路----------------------
1楼的说法不准确。
getLength不是const。如果otherS是const,那么就不允许调用otherS.getLength()
要改成
int getLength ( ) const;