Creative Code

stack2(extern,explicit사용) 본문

C++ Programming

stack2(extern,explicit사용)

빛하루 2023. 9. 6. 11:52

※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_];

}

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

safeArray(배열 크기)  (0) 2023.09.06
stack3(stack,array클래스 연결)  (0) 2023.09.06
array(array 클래스)  (0) 2023.09.05
list2(linked list 클래스 연결)  (0) 2023.09.05
string4(reference counting사용)  (0) 2023.09.05