반응형

7.10> 스택 클래스 Stack을 만들고 푸시(push)용으로 <<연산자를, (pop)을 위해 >> 연산자를, 비어 있는 스택인지를 알기 위해 ! 연산자를 작성하라. 다음 코드를 main()으로 작성하라.

<코드>

#include <iostream>

 

using namespace std;

class Stack{

private:

        int stk[5]; //크기 5짜리 스택

        int index;

public:

        Stack(int index=-1); //디폴트 매개변수 인덱스 = -1(empty)

        Stack& operator<<(int op); //푸시

        friend bool operator!(Stack op);

        void operator>>(int &op); //

};

Stack::Stack(int index){this->index=index;} //index 초기화

Stack& Stack::operator<<(int op){ //푸시 구현

        index++; //인덱스 증가

        stk[index]=op; //오퍼랜드를 해당 인덱스에 넣어줌

        return *this; //현재 객체의 참조 반환

}

bool operator!(Stack op){ //비어있는지 확인

        if(op.index==-1)

               return true; //비었으면 true 리턴

        else

               return false;

}

void Stack::operator>>(int &op){

        index--; //인덱스 감소

        op= stk[index+1]; //제일 위의 원소 pop

}

int main(void){

        Stack stack;

        stack<<3<<5<<10; //3,5,10 순서의 스택

        while(true){

               if(!stack) break;

               int x;

               stack>>x; //제일 위의 원소부터 나옴

               cout<<x<<" ";

        }

        cout << endl;

        return 0;

}

 

<결과창>

               

                    


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

MyStack Class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
Statistics class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
Circle class  (0) 2017.12.25

+ Recent posts