C++ Programming
stack3(stack,array클래스 연결)
빛하루
2023. 9. 6. 11:53
※main.cpp파일
#include <iostream>
#include "stack.h"
int main()
{
Stack s1(10);
Stack s2(100);
s1.push(100); //구조체 자료는 인자를 전달할 때 오버헤드를 줄이기 위해 포인터를 쓴다.
s1.push(200);
s1.push(300);
std::cout << "s1 1st pop() : " << s1.pop() <<std::endl;
std::cout << "s1 2nd pop() : " << s1.pop() <<std::endl;
std::cout << "s1 3rd pop() : " << s1.pop() <<std::endl;
s2.push(900);
s2.push(800);
s2.push(700);
std::cout << "s2 1st pop() : " << s2.pop() <<std::endl;
std::cout << "s2 2nd pop() : " << s2.pop() <<std::endl;
std::cout << "s2 3rd pop() : " << s2.pop() <<std::endl;
return 0;
}
※stack.h파일
#ifndef STACK_H
#define STACK_H
#include "array.h"
class Stack {
private:
static const int STACKSIZE;
Array arr_; //클래스안에 클래스타입의 멤버를 가지는 관계를 'has-a'관계라 한다.
int tos_;
Stack(const Stack& rhs);
Stack& operator=(const Stack& rhs);
public:
explicit Stack(int size = Stack::STACKSIZE);
~Stack();
bool isFull() const;
bool isEmpty() const;
void push(int data);
int pop();
};
#endif
※stack.cpp파일
#include "stack.h"
#include <cassert>
const int STACKSIZE = Array::getDefaultSize();
Stack::Stack(int size)
:arr_(size), tos_(0)
{
}
Stack::~Stack()
{
}
bool Stack::isFull() const {
return tos_ == arr_.size();
}
bool Stack::isEmpty() const {
return tos_ == 0;
}
void Stack::push(int data) {
assert(!isFull());
arr_[tos_] = data;
++tos_;
}
int Stack::pop() {
assert(!isEmpty());
--tos_;
return arr_[tos_];
}