C++ Programming
stack4(template사용)
빛하루
2023. 9. 8. 11:38
※main.cpp파일
#include <iostream>
#include "stack.h"
int main() {
Stack<int>s1;
s1.push(100);
s1.push(200);
s1.push(300);
std::cout << "s1 first pop() : " << s1.pop() << std::endl;
std::cout << "s1 second pop() : " << s1.pop() << std::endl;
std::cout << "s1 third pop() : " << s1.pop() << std::endl;
Stack<double>s2;
s2.push(1.1);
s2.push(2.2);
s2.push(3.3);
std::cout << "s2 first pop() : " << s2.pop() << std::endl;
std::cout << "s2 second pop() : " << s2.pop() << std::endl;
std::cout << "s2 third pop() : " << s2.pop() << std::endl;
return 0;
}
※stack.h파일
#ifndef STACK_H
#define STACK_H
#include "array.h"
#include <cassert>
template <typename T>
class Stack {
private:
static const int STACKSIZE;
Array<T> arr_; //클래스안에 클래스타입의 멤버를 가지는 관계를 'has-a'관계라 한다.
int tos_;
Stack(const Stack<T>& rhs);
Stack<T>& operator=(const Stack<T>& rhs);
public:
explicit Stack(int size = Stack<T>::STACKSIZE);
~Stack();
bool isFull() const;
bool isEmpty() const;
void push(const T& data);
const T pop();
};
template <typename T>
const int Stack<T>::STACKSIZE = Array<T>::getDefaultSize();
template <typename T>
Stack<T>::Stack(int size)
:arr_(size), tos_(0)
{
}
template <typename T>
Stack<T>::~Stack()
{
}
template <typename T>
bool Stack<T>::isFull() const {
return tos_ == arr_.size();
}
template <typename T>
bool Stack<T>::isEmpty() const {
return tos_ == 0;
}
template <typename T>
void Stack<T>::push(const T& data) {
assert(!isFull());
arr_[tos_] = data;
++tos_;
}
template <typename T>
const T Stack<T>::pop() {
assert(!isEmpty());
--tos_;
return arr_[tos_];
}
#endif