printf("ho_tari\n");

Stack2 (extern, explicit) 본문

C++

Stack2 (extern, explicit)

호타리 2023. 9. 7. 09:24

<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



class Stack {

private:

	int *pArr_;

	int size_;

	int tos_;

	

	Stack(const Stack& rhs);

	Stack& operator=(const Stack& rhs);

	

	static const int STACKSIZE;

public:

	// Stack() {}

	// Stack(const Stack& rhs) {/*memberwise copy */}

	// ~Stack() {}

	// Stack& operator=(const Stack& rhs) {/*memberwise copy*/}

	// Stack *operator&() { return this;}

	// const Stack *operator&() const {return this;}

	

	explicit Stack(int size = STACKSIZE);

	~Stack();

	

	bool isFull() const;

	bool isEmpty() const;

	

	void push(int data);

	int pop();

	

	

	

};



#endif

 

<stack.cpp>

#include "stack.h"

#include <cassert>



const int Stack::STACKSIZE = 100;



Stack::Stack(int size)

: pArr_(new int[size]), size_(size), tos_(0)

{

	assert(pArr_);

}



Stack::~Stack() {

	delete[] pArr_;

}



bool Stack::isFull() const{

	return tos_ == size_;

}



bool Stack::isEmpty() const{

	return tos_ == 0;

}



void Stack::push(int data) {

	assert(!isFull());

	pArr_[tos_] = data;

	++tos_;

}



int Stack::pop() {

	assert(!isEmpty());	

	--tos_;

	return pArr_[tos_];

}

 

<compile 결과>

'C++' 카테고리의 다른 글

Queue3 (array 클래스와 has-a 관계)  (0) 2023.09.07
Queue2 (생성자 초기화 리스트, static member, explicit)  (0) 2023.09.07
Array (array 클래스)  (0) 2023.09.07
Linked List  (0) 2023.09.05
String (클래스 개선)  (0) 2023.09.05