반응형

9.6> 다음 AbstractStack은 정수 스택 클래스로서 추상 클래스이다. 이를 상속받아 정수를 푸시, 팝하는 IntStack 클래스를 만들고 사용 사례를 보여라.

<코드>

#include <iostream>

using namespace std;

class AbstractStack{

public:

        virtual bool push(int n)=0; //스택에 n 푸시한다. 스택이 full이면 false 리턴

        virtual bool pop(int &n)=0; //스택에서 팝한 정수를 n 저장하고 스택이 empty이면 false 리턴

        virtual int size()=0; //현재 스택에 저장된 정수의 개수 리턴

};

class IntStack : public AbstractStack{

private:

        int *p;

        int cap; //전체 크기(배열 크기)

        int index; //인덱스 -1 empty

public:

        IntStack(int cap,int index);

        ~IntStack();

        bool push(int n);

        bool pop(int &n);

        int size();

        void show();

};

IntStack::IntStack(int cap,int index=-1) { //cap 만큼 동적 배열 생성

        this->cap=cap;

        this->index=index;

        p=new int[cap];}

 

IntStack::~IntStack(){delete []p;} //동적 배열 반환

bool IntStack::push(int n){ //배열 끝에 원소 추가, 꽉찼으면 false 리턴

        index++;

        if(index>=cap) {index--; return false;}

        else {p[index]=n; return true;}

}

bool IntStack::pop(int &n){ //마지막 원소 pop, 텅비었으면 false 리턴

        int tmp=p[index];

        index--;

        if(index<-1) {index++; return false;}

        else{n=tmp; return true;} //인자로 받은 참조에 pop 값을 넣는다.

}

void IntStack::show(){ //현재 존재하는 원소 순회 출력

        for(int i=0;i<index+1;i++){cout<<p[i]<<" ";}

        cout<<endl;

}

int IntStack::size() {return index+1;} //현재 존재하는 원소 개수

int main(void){

        int pp; //팝된 정수를 넣을 변수

        IntStack is(5); //cap 5짜리 인트 스택

        int getpush=0; //푸시할 정수를 받을 변수

        while(1){

       

        int menu=0; //메뉴 선택용 변수

        cout<<"1.푸시 2. 3.저장된 개수 (종료는 -1) >> ";

        cin>>menu;

        if(menu==1){ //1이면 푸시

               int ps;

               cout<<"푸시 정수를 입력하세요>> ";

               cin>>ps;

               if(is.push(ps)){cout<<"푸시 성공!"<<endl;} else{cout<<"푸시 실패!"<<endl;}

               is.show();

        }

        else if(menu==2){ //2

               if(is.pop(pp)){cout<<" 성공! 정수 : "<<pp<<endl;}else{cout<<" 실패!"<<endl;}

               is.show();

        }

        else if(menu==3){ //3이면 개수 출력

               cout<<"현재 길이 : "<<is.size()<<endl;

               is.show();    

        }

        else if(menu==-1){break;} //-1이면 루프

        else{cout<<"잘못된 입력입니다."<<endl;

        cin.clear();

        cin.ignore(100,'\n'); //문자 입력시 버퍼 비워주기 위함..

        continue;} //이상한 입력하면 다시 메뉴

        }

        return 0;

}

 

<결과창>


반응형

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

논리 게이트  (0) 2017.12.31
while, do while loop class  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
반응형

9.5> 디지털 회로에서 기본적인 게이트로 OR 게이트, AND 게이트, XOR 게이트 등이 있다. 이들은 각각 두 입력 신호를 받아 OR 연산, AND 연산, XOR 연산을 수행한 결과를 출력한다. 이 게이트들을 각각 ORGate, XORGate, ANDGate 클래스로 작성하고자 한다. ORGate, XORGate, ANDGate 클래스가 AbstractGate를 상속받도록 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class AbstractGate{ //추상 클래스

protected:

        bool x,y;

public:

        void set(bool x, bool y){this->x=x; this->y=y;}

        virtual bool operation()=0;

};

 

 

class ANDGate : public AbstractGate{

public:

        virtual bool operation();

};

bool ANDGate::operation(){return x&y;} //x y 비트and 연산 리턴

 

class ORGate : public AbstractGate{

public:

        virtual bool operation();

};

bool ORGate::operation(){return x|y;} //x y 비트or 연산 리턴

 

class XORGate : public AbstractGate{

public:

        virtual bool operation();

};

bool XORGate::operation(){return x^y;} //x y 비트xor연산 리턴

 

int main(void){

        ANDGate and;

        ORGate or;

        XORGate xor;

 

        and.set(true,false);

        or.set(true,false);

        xor.set(true,false);

        cout.setf(ios::boolalpha); //불린 값을 "true", "false"문자열로 출력할 것을 지시

        cout<<and.operation()<<endl; //AND 결과는 false

        cout<<or.operation()<<endl; //OR 결과는 true

        cout<<xor.operation()<<endl; //XOR 결과는 true

        return 0;

}

 

 

<결과창>


반응형

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

추상 클래스 상속 (Int Stack)  (0) 2017.12.31
while, do while loop class  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
반응형

9.4> LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록 WhileLoopAdder, DoWhileLoopAdder 클래스를 작성하라. While , do-while 문을 이용하여 합을 구하도록 calculate() 함수를 각각 작성하면 된다.

<코드>

#include<iostream>

#include<string>

 

using namespace std;

 

class LoopAdder{  //추상 클래스

      string name;  //루프의 이름

      int x, y, sum;  //x에서 y까지의 합은 sum

      void read();  //x, y 값을 읽어 들이는 함수

      void write();  //sum 출력하는 함수

protected:

      LoopAdder(string name = ""){

            this->name = name;

      }  //루프의 이름을 받는다. 초깃값은 ""

      int getX(){ return x; }

      int getY(){ return y; }

      virtual int calculate() = 0;  //순수 가상 함수. 루프를 돌며 합을 구하는 함수

public:

      void run();  //연산을 진행하는 함수

};

 

void LoopAdder::read(){ //x, y 입력

      cout << name << ":" << endl;

      cout << "처음 수에서 두번째 수까지 더합니다. 수를 입력하세요 >>";

      cin >> x >> y;

}

 

void LoopAdder::write(){

     cout << x << "에서 " << y << "까지의 = " << sum << " 입니다" << endl;

     //결과 sum 출력

}

 

void LoopAdder::run(){

      read();  //x, y 읽는다.

      sum = calculate();  //루프를 돌면서 계산한다.

      write();  //결과 sum 출력한다.

}

 

 

 

class WhileLoopAdder : public LoopAdder{

public:

        WhileLoopAdder(string name);

protected:

        virtual int calculate();

};

WhileLoopAdder::WhileLoopAdder(string name=""):LoopAdder(name){} //생성자

int WhileLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        int check=from;

        while(check<=to){sum+=check;check++;} //check to이하이면 실행

        return sum;

}

 

class DoWhileLoopAdder : public LoopAdder{

public:

        DoWhileLoopAdder(string name);

protected:

        virtual int calculate();

};

DoWhileLoopAdder::DoWhileLoopAdder(string name=""):LoopAdder(name){} //생성자

int DoWhileLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        int check=from;

        do{sum+=check;check++;}while(check<=to); //무조건 처음은 실행, 그이후 check to 이하일때만 실행

        return sum;

}

 

int main(void){

        WhileLoopAdder whileLoop("While Loop");

        DoWhileLoopAdder doWhileLoop("Do while Loop");

 

        whileLoop.run();

        doWhileLoop.run();

        return 0;

}

 

 

<결과창>


반응형

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

추상 클래스 상속 (Int Stack)  (0) 2017.12.31
논리 게이트  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
반응형

9.3> LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록 ForLoopAdder 클래스를 작성하라. ForLoopAdder 클래스의 calculate() 함수는 for 문을 이용하여 합을 구한다.

<코드>

#include<iostream>

#include<string>

 

using namespace std;

 

class LoopAdder{  //추상 클래스

      string name;  //루프의 이름

      int x, y, sum;  //x에서 y까지의 합은 sum

      void read();  //x, y 값을 읽어 들이는 함수

      void write();  //sum 출력하는 함수

protected:

      LoopAdder(string name = ""){

            this->name = name;

      }  //루프의 이름을 받는다. 초깃값은 ""

      int getX(){ return x; }

      int getY(){ return y; }

      virtual int calculate() = 0;  //순수 가상 함수. 루프를 돌며 합을 구하는 함수

public:

      void run();  //연산을 진행하는 함수

};

 

void LoopAdder::read(){ //x, y 입력

      cout << name << ":" << endl;

      cout << "처음 수에서 두번째 수까지 더합니다. 수를 입력하세요 >>";

      cin >> x >> y;

}

 

void LoopAdder::write(){//결과 sum 출력

     cout << x << "에서 " << y << "까지의 = " << sum << " 입니다" << endl;

    }

 

void LoopAdder::run(){

      read();  //x, y 읽는다.

      sum = calculate();  //루프를 돌면서 계산한다.

      write();  //결과 sum 출력한다.

}

 

class ForLoopAdder : public LoopAdder{

public:

        ForLoopAdder(string name);

protected:

        virtual int calculate();

};

ForLoopAdder::ForLoopAdder(string name=""):LoopAdder(name){} //생성자

int ForLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        for(int i=from;i<to+1;i++){sum+=i;}

        return sum; //from에서 to까지 순차적으로 더한 리턴

}

int main(void){

        ForLoopAdder forLoop("For Loop: ");

        forLoop.run();

        return 0;

}

 

<결과창>


반응형

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

논리 게이트  (0) 2017.12.31
while, do while loop class  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31

+ Recent posts