用模板设计一个堆栈类,包含判栈、读栈、入栈和出栈功能,要求用成员函数重载“()”实现判栈功能,用友

2025-05-13 12:15:20
推荐回答(1个)
回答1:

重载“-”为出栈?“<<”?
判栈有判空和判满。
#include
using namespace std;
template

class Stack
{
private:
int size;
int top;
T *space;
public:
Stack(int n);
~Stack()
{
delete [] space;
}

void push( T t);

friend ostream& operator<<(ostream& out,Stack &st)
{
while(!(st.operator()()))
out<< st.space[st.top++]< return out;
}

bool operator ()() const
{
return top == size;
}

bool Isfull() const
{
return top == 0;
}
};

template
Stack::Stack(int size)
{
this->size = size;
top = size;
space = new T [size];
}

template
void Stack::push(T t)
{
if(!Isfull())
space[--top] = t;
}

int main()
{
Stacks(20);//可以指定栈的大小
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);

cout<}
这个没问题,如果是重载 - 改为:
#include
using namespace std;
template

class Stack
{
private:
int size;
int top;
T *space;
public:
Stack(int n);
~Stack()
{
delete [] space;
}

void push( T t);

friend Stack & operator -(Stack &st)
{
while(!(st.operator()()))
cout<< st.space[st.top++]<
}

bool operator ()() const
{
return top == size;
}

bool Isfull() const
{
return top == 0;
}
};

template
Stack::Stack(int size)
{
this->size = size;
top = size;
space = new T [size];
}

template
void Stack::push(T t)
{
if(!Isfull())
space[--top] = t;
}

int main()
{
Stacks(20);//可以指定栈的大小
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);

-s;
}
但是这个在VC下不行,在codeblocks下使用mingw32-g++.exe可以正常编译执行,运行截图:
请参考