printf("ho_tari\n");
Queue3 (array 클래스와 has-a 관계) 본문
<main.cpp>
#include <iostream>
#include "queue.h"
int main()
{
//Queue q1; // Queue q1(100);
//Queue q2(10); // Queue q2 = 10;
//Queue q3 = q2;
//q1 = q2;
Queue s1(10), s2(100);
s1.push(100);
s1.push(200);
std::cout << "s1 1st pop() : " << s1.pop() << std::endl;
s1.push(300);
std::cout << "s1 2nd pop() : " << s1.pop() << std::endl;
std::cout << "s1 3rd pop() : " << s1.pop() << std::endl;
s2.push(900);
s2.push(800);
std::cout << "s2 1st pop() : " << s2.pop() << std::endl;
s2.push(700);
std::cout << "s2 2nd pop() : " << s2.pop() << std::endl;
std::cout << "s2 3rd pop() : " << s2.pop() << std::endl;
return 0;
}
<queue.h>
#ifndef QUEUE_H
#define QUEUE_H
//#define QUEUESIZE 100
#include "array.h"
class Queue {
public:
//Queue *operator&() { return this; }
//const Queue *operator&() const { return this; }
//Queue();
explicit Queue(int size = Queue::QUEUESIZE);
~Queue();
bool isFull() const;
bool isEmpty() const;
void push(int data);
int pop();
private:
static const int QUEUESIZE;
//int *pArr_;
//int size_;
Array arr_; // 'has-a'
int front_;
int rear_;
Queue(const Queue& rhs);
Queue& operator=(const Queue& rhs);
};
#endif
<queue.cpp>
#include "queue.h"
#include <cassert>
const int Queue::QUEUESIZE = 100;
Queue::Queue(int size)
: arr_(size), front_(0), rear_(0)
{
}
Queue::~Queue()
{
}
bool Queue::isFull() const
{
// return rear_ == size_;
return (rear_ + 1) % arr_.size() == front_;
}
bool Queue::isEmpty() const
{
return front_ == rear_;
}
void Queue::push(int data)
{
assert(!isFull() );
arr_[rear_] = data; // this->arr_.operator[](this->rear_)
// ++rear_;
rear_ = (rear_ + 1) % arr_.size();
}
int Queue::pop()
{
assert(!isEmpty() );
int i = front_;
//++front_;
front_ = (front_ + 1) % arr_.size();
return arr_[i];
}
<compile 결과>
'C++' 카테고리의 다른 글
SafeArray2 (상속) (0) | 2023.09.07 |
---|---|
SafeArray (0) | 2023.09.07 |
Queue2 (생성자 초기화 리스트, static member, explicit) (0) | 2023.09.07 |
Stack2 (extern, explicit) (0) | 2023.09.07 |
Array (array 클래스) (0) | 2023.09.07 |