C++
9장 실습문제_6번
림가이드
2020. 12. 31. 17:15
6. 다음 AbstractStack은 정수 스택 클래스로서 추상 클래스이다.
class AbstractStack {
public:
virtual bool push(int n) = 0; //스택에 n푸시. 스택full이면 false 리턴
virtual bool pop(int& n) = 0; //스택에서 팝한 정수를 n에 저장. 스택empty이면 ture리턴
virtual int size() = 0; //현재 스택에 저장된 정수의 개수 리턴
};
이를 상속받아 정수를 푸시,팝하는 IntStack클래스를 만들고 사용사례를 보여라.
-결과
-답
#include <iostream>
using namespace std;
class AbstractStack {
public:
virtual bool push(int n) = 0;
virtual bool pop(int& n) = 0;
virtual int size() = 0;
};
class IntStack :public AbstractStack {
int top;
int max;
int* pStack;
public:
IntStack(int num) { pStack = new int[num]; max = num; top = -1; }
bool push(int n) {
if (top == max)
return false;
else {
top++;
pStack[top]=n;
return true;
}
}
bool pop(int& n) {
if (top == -1)
return false;
else {
n = pStack[top];
top--;
return true;
}
}
int size() {
return top + 1;
}
};
int main() {
IntStack stk(50);
int re;
stk. push(10);
stk.push(20);
stk.push(30);
stk.push(40);
cout << "현재 원소 개수 : " << stk.size() << "개" << endl;
stk.pop(re);
cout << "pop : " << re << endl;
stk.pop(re);
cout << "pop : " << re << endl;
stk.pop(re);
cout << "pop : " << re << endl;
cout << "현재 원소 개수 : " << stk.size() << "개" << endl;
}