Notice
                              
                          
                        
                          
                          
                            Recent Posts
                            
                        
                          
                          
                            Recent Comments
                            
                        
                          
                          
                        
                    Creative Code
main.cpp(스택) 본문
※main.cpp 파일
#include <iostream>
#include "stack.h"
int main()
{
	Stack s1(10), 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
class Stack {
private:
	int *array;
	int tos;
	int size;
public:
	Stack(int size); // constructor(생성자)는 함수이름을 구조체 이름으로 설정한다. 타입은 x (c언어에서 initstack함수)
	~Stack();        // destructor (소멸자) (c언어에서 cleanupstack함수)
	void push(int data);
	int pop();
};
#endif※stack.cpp 파일
#include <cassert> 
#include "stack.h"
Stack::Stack(int size)  //생성자
{
	this ->array = new int[size];
	assert(this->array); 
	this->size = size;
	this->tos = 0;
}
Stack::~Stack()  //소멸자
{
	delete[] this ->array;
}
void Stack::push(int data)
{
	assert(this->tos != this->size);
	this->array[this->tos] = data;
	++this->tos;
}
int Stack::pop()
{
	assert(this->tos!= 0);
	--this->tos;
	return this->array[this->tos];
}'C++ Programming' 카테고리의 다른 글
| main.cpp(Rational 사칙연산) (0) | 2023.08.30 | 
|---|---|
| main.cpp(complex 연산) (0) | 2023.08.30 | 
| main.cpp(complex 클래스) (0) | 2023.08.30 | 
| main.cpp(linked list) (0) | 2023.08.29 | 
| main.cpp(queue) (0) | 2023.08.29 |