반응형

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
반응형

9.2> Converter 클래스를 상속받아 km mile(마일)로 변환하는 KmToMile 클래스를 작성하라. Main() 함수와 실행 결과는 다음과 같다.

<코드>

#include <iostream>

#include <string>

using namespace std;

 

class Converter {

protected:

        double ratio;

        virtual double convert(double src) = 0; //src 다른 단위로 변환한다.

        virtual string getSourceString() = 0; //src 단위 명칭

        virtual string getDestString() = 0; //dest 단위 명칭

public:

        Converter(double ratio) { this->ratio = ratio; }

        void run() {

               double src;

               cout << getSourceString() << " " << getDestString() << " 바꿉니다. ";

               cout << getSourceString() << " 입력하세요>> ";

               cin >> src;

               cout << "변환 결과 : " << convert(src) << getDestString() << endl; //src 받아서 컨버팅

        }

};

 

class KmToMile : public Converter{

protected:

        string from; //바뀌어지는 것의 이름

        string to; //바뀐 결과의 이름

public:

        KmToMile(double ratio, string from, string to);

        virtual double convert(double src);

        virtual string getSourceString();

        virtual string getDestString();

};

KmToMile::KmToMile(double ratio,string from="Km",string to="Mile"):Converter(ratio){

        this->from = from;

        this->to = to;

        this->ratio = ratio; //생성자 from,to,ratio 초기화 from to 디폴트는 "Km" "Mile"

}

double KmToMile::convert(double src){return src/ratio;}

string KmToMile::getSourceString() { return from; } //겟소스스트링 함수 오버라이딩

string KmToMile::getDestString() { return to; } //dest스트링 함수 오버라이딩

 

int main(void){

        KmToMile toMile(1.609344); //1 mile 1.609344 Km

        toMile.run();

        return 0;

}

 

<결과창>

                                   


반응형

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

while, do while loop class  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
반응형

9.1> Converter 클래스를 상속받아 달러를 원화로 환산하는 WonToDollar 클래스를 작성하라. Main() 함수와 실행 결과는 다음과 같다.

<코드>

#include <iostream>

#include <string>

using namespace std;

 

class Converter {

protected:

        double ratio;

        virtual double convert(double src) = 0; //src 다른 단위로 변환한다.

        virtual string getSourceString() = 0; //src 단위 명칭

        virtual string getDestString() = 0; //dest 단위 명칭

public:

        Converter(double ratio) { this->ratio = ratio; }

        void run() {

               double src;

               cout << getSourceString() << " " << getDestString() << " 바꿉니다. ";

               cout << getSourceString() << " 입력하세요>> ";

               cin >> src;

               cout << "변환 결과 : " << convert(src) << getDestString() << endl; //src 받아서 컨버팅

        }

};

class WonToDollar : public Converter { //컨버터 클래스를 상속받은 원투달라 클래스

protected:

        string from; //바뀌어지는 것의 이름

        string to; //바뀐 결과의 이름

public:

        WonToDollar(double ratio, string from, string to);

        virtual double convert(double src);

        virtual string getSourceString();

        virtual string getDestString();

};

WonToDollar::WonToDollar(double ratio, string from = "", string to = "달러") : Converter(ratio) {

        this->from = from;

        this->to = to;

        this->ratio = ratio; //생성자 from,to,ratio 초기화 from to 디폴트는 "" "달러"

}

double WonToDollar::convert(double src) {

        return (src/ratio); //src/ratio 리턴, 컨버트 함수 오버라이딩

}

string WonToDollar::getSourceString() { return from; } //겟소스스트링 함수 오버라이딩

string WonToDollar::getDestString() { return to; } //dest스트링 함수 오버라이딩

 

int main(void) {

        WonToDollar wd(1010); //비율을 1010으로 해서 객체 생성

        wd.run(); //컨버팅 실행

        return 0;

}

 

<결과창>

                                

   


반응형

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

ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
반응형

8.8> 다음 그림과 같은 상속 구조를 갖는 클래스를 설계한다. 모든 프린터는 모델명(model), 제조사(manufacturer), 인쇄 매수(printedCount), 인쇄 종이 잔량(availableCount)을 나타내는 정보와 print(int pages) 멤버 함수를 가지며, print()가 호출할 때마다 pages 매의 용지를 사용한다. 잉크젯 프린터는 잉크 잔량(availableInk) 정보와 printInkJet(int pages) 멤버 함수를 추가적으로 가지며, 레이저 프린터는 토너 잔량(availableToner) 정보와 역시 printLaser(int pages) 멤버 함수를 추가적으로 가진다. 각 클래스에 적절한 접근 지정으로 멤버 변수와 함수, 생성자, 소멸자를 작성하고, 다음과 같이 실행되도록 전체 프로그램을 완성하라. 잉크젯 프린터 객체와 레이저 프린터 객체를 각각 하나만 동적 생성하여 시작한다.

<코드>

#include <iostream>

#include <string>

 

using namespace std;

 

class Printer { //프린터 클래스

protected:

        string model; //모델명 스트링

        string manufacturer; //제조사명 스트링

        int printedcount; // 출력된 매수

        int availableCount; // 앞으로 출력 가능한 매수

        int print(int pages); //프린트 원형 함수

        Printer(string model, string manufacturer, int availableCount); //생성자

        void show(); // 화면 출력 함수

};

class InkjetPrinter : public Printer { //프린터를 상속받은 잉크젯 프린터 클래스

private:

        int availableInk; //잉크잔량

public:

        InkjetPrinter(string model, string manufacturer, int availableCount,int availableInk); //생성자

        void printInkJet(int pages); //잉크젯 프린트 함수

        void inkjetshow(); //잉크젯 화면 출력 함수

};

class LaserPrinter : public Printer { //프린터를 상속받은 레이저 프린터 클래스

private:

        float availableToner; //토너잔량

public:

        LaserPrinter(string model, string manufacturer, int availableCount, float availableToner); //생성자

        void printLaser(int pages); //레이저 프린트 함수

        void lasershow(); //레이저 화면 출력 함수

};

Printer::Printer(string model, string manufacturer, int availableCount) {

        this->model = model;

        this->manufacturer = manufacturer;

        this->printedcount = 0; //객체 생성시 한장도 안뽑았으므로 0

        this->availableCount = availableCount;

}

int Printer::print(int pages) {

        if (availableCount - pages < 0) { cout << "용지가 부족하여 프린트 없습니다." << endl; return 0; }

        else { availableCount -= pages; printedcount += pages;  return 1; }

} //사용가능한 용지보다 뽑아야하는 용지 수가 많으면 fail, 아니면 success 이때는 사용가능 페이지를 사용한 만큼 - 해준다. 그리고 사용한 페이지를 +해준다.

        //리턴 타입을 정해준 이유는 아래 프린트잉크젯이나 프린트레이저에서 프린트가 가능 때만 if문이 실행되게 하기 위해서 그렇다.

 

void Printer::show() {

        cout << this->model << ", " << this->manufacturer << ", " << "남은 종이" << this->availableCount << "";

} //모델명, 제조사명, 남은종이 출력

 

InkjetPrinter::InkjetPrinter(string model, string manufacturer, int availableCount, int availableInk) : Printer(model, manufacturer, availableCount) {

        this->availableInk = availableInk;} //프린터 생성자와 동시에 사용가능잉크 입력

void InkjetPrinter::printInkJet(int pages) {if (print(pages)) {

        if(availableInk-pages<0){ cout << "잉크가 부족하여 프린트 없습니다." << endl; availableCount+=pages;} //잉크 부족시 에러

        else {cout << "프린트하였습니다." << endl; availableInk -= pages;} }} //페이지 수만큼 출력가능하면 잉크 그만큼 -해줌.

void InkjetPrinter::inkjetshow() {

        show(); cout << ", 남은 잉크 " << this->availableInk << endl;} //print show 실행 남은 잉크 출력

 

LaserPrinter::LaserPrinter(string model, string manufacturer, int availableCount, float availableToner) : Printer(model, manufacturer, availableCount) {

        (this->availableToner) = (float)availableToner; } //프린터 생성자와 동시에 사용가능토너 입력

 

void LaserPrinter::printLaser(int pages) { if (print(pages)) {

        if((float)(availableToner*2)-(float)pages<0){ cout << "토너가 부족하여 프린트 없습니다." << endl; availableCount+=pages;} //토너 부족시 에러

        else {cout << "프린트하였습니다." << endl; (float)availableToner -= ((float)pages/2);} } } // 페이지 수만큼 출력가능하면 토너 그것의 1/2만큼 - 해줌.

void LaserPrinter::lasershow() {

        show(); cout << ", 남은 잉크 " << (float)(this->availableToner) << endl;} //print show 실행 남은 토너 출력

 

int main(void) {

        char check = 0; // check y/n 나타낸다.

        InkjetPrinter ip("Officejet V40", "HP", 20, 10); // 잉크젯프린터 ip 생성

        LaserPrinter lp("SCX-6x45", "삼성전자", 30, 10.0); // 레이저프린터 lp 생성

        cout << "현재 작동 중인 2 대의 프린터는 아래와 같다." << endl;

        cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

        while (1) {

               cout << "프린터(1:잉크젯, 2:레이저) 매수 입력>> ";

               int which = 0; int pg = 0; //which 잉크젯과 레이저를 구분

               cin >> which >> pg; cin.ignore(100, '\n'); //개행문자 삭제를 위하여 ignore 사용

               if (which == 1) { //잉크젯이면

                       ip.printInkJet(pg); //pg만큼 출력한다.

                       cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

                      

                      

                       while (1) {

                              cout << "계속 프린트 하시겠습니까?(y/n)>>";

                              check=cin.get(); cin.ignore(100, '\n'); //'y','n' 받고 개행문자 없애기 위함.

                              if (check == 'y'||check=='n') { break; } //'y' 'n'이면 브레이크

                              else { cout << "잘못된 입력입니다." << endl; continue; } //이상한 들어오면 다시 실행

                       }

                       if (check=='y') continue; else if (check=='n') break//y 루프 처음으로 n이면 브레이크

               }

               else if (which == 2) { //레이저면

                       lp.printLaser(pg); //pg만큼 출력한다.

                       cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

                       while (1) {

                              cout << "계속 프린트 하시겠습니까?(y/n)>>";

                              check = cin.get(); cin.ignore(100, '\n'); //'y','n' 받고 개행문자 없애기 위함.

                              if (check == 'y' || check == 'n') { break; }  //'y' 'n'이면 브레이크

                              else { cout << "잘못된 입력입니다." << endl; continue; } //이상한 들어오면 다시 실행

                       }

                       if (check == 'y') continue; else if (check == 'n') break; //y 루프 처음으로 n이면 브레이크

               }

               else { cout << "잘못된 입력입니다." << endl; continue; } //which 1이나 2가아니면 출력되는 에러

        }

        return 0;

}

 

 

 

<결과창>


반응형

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

KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
반응형

8.7> 아래와 같은 BaseMemory 클래스를 상속받는 ROM(Read Only Memory), RAM 클래스를 작성하라. BaseMemory에 필요한 코드를 수정 추가하여 적절히 완성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseMemory { //베이스메모리 클래스

private:

        char *mem; //캐릭터 동적 배열을 가리킬 포인터 mem

protected:

        BaseMemory(int size) { mem = new char[size]; } //생성자 mem size만큼의 캐릭터 동적 배열 할당

        void burn(int index, char value);

public:

        char read(int index);

 

};

class ROM : public BaseMemory { //베이스메모리를 상속받은 롬 클래스

public:

        ROM(int memsize, char *arr, int arrsize);

};

 

class RAM : public BaseMemory { //베이스메모리를 상속받은 램 클래스

public:

        RAM(int memsize);

        void write(int i, char value);

};

 

void BaseMemory::burn(int index, char value) { mem[index] = value; } //mem 배열의 해당 index value 삽입

 

char BaseMemory::read(int index) { return mem[index]; } //mem 배열의 해당 index 원소 리턴

 

ROM::ROM(int memsize, char *arr, int arrsize) : BaseMemory(memsize) { //롬 생성자, 베이스 메모리 생성자 실행하고

        for (int i = 0; i < arrsize; i++) { burn(i, arr[i]); } //arr이 가리키는 배열의 원소 ROM에 굽는다.

}

RAM::RAM(int memsize) : BaseMemory(memsize) {} //단순히 memsize의 캐릭터 동적 배열만 할당한다.(베이스메모리 컨스트럭터와 동일)

 

void RAM::write(int i, char value) { burn(i, value); } //램에 존재하는 캐릭터 배열 인덱스 i value값을 삽입한다.

 

int main(void) {

        char x[5] = { 'h','e','l','l','o' }; //캐릭터배열 크기 5

        ROM biosROM(1024 * 10, x, 5); //10KB ROM 메모리, 배열 x로 초기화됨.

        RAM mainMemory(1024 * 1024); //1MB RAM 메모리

 

                                                              //0번지에서 4번지까지 biosROM에서 읽어 mainMemory에 복사

        for (int i = 0; i < 5; i++) { mainMemory.write(i, biosROM.read(i)); }

        //램 메인메모리에 있는 캐릭터 배열의 i인덱스에 롬 바이오스롬에 들어있는 캐릭터 배열의 i인덱스 원소를 삽입한다.

        for (int i = 0; i < 5; i++) { cout << mainMemory.read(i); } //메인메모리에 있는 캐릭터배열 0~4인덱스 원소를 순회하고 출력한다.

 

        return 0;

}

<결과창>

 


반응형

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

WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
반응형

8.6> BaseArray 클래스를 상속받아 스택으로 작동하는 MyStack 클래스를 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseArray{

private:

        int capacity;//배열의 크기

        int *mem;//정수 배열을 만들기 위한 메모리의 포인터

protected:

        BaseArray(int capacity=100){ //디폴트 매개변수 100

               this->capacity=capacity;

               mem=new int[capacity]; //캐패시티 크기로 동적 배열 형성

        }

        ~BaseArray(){delete []mem;} //동적 메모리 힙으로 반환

        void put(int index, int val){mem[index]=val;} //인덱스에 매개변수 삽입

        int get(int index){return mem[index];} //해당 인덱스에서 정수 가져옴

        int getCapacity(){return capacity;} //용량 리턴

};

 

class MyStack : public BaseArray{

private:

        int rear; //마지막 인덱스 리어

public:

        MyStack(int capacity,int rear);

        void push(int arg); //마지막에 원소 추가

        int capacity(); //스택 용량

        int length(); //스택 길이

        int pop(); //마지막 원소 꺼내옴

};

MyStack::MyStack(int capacity=100,int rear=-1):BaseArray(capacity) {this->rear=rear;}

void MyStack::push(int arg) {rear++; put(rear,arg);}

int MyStack::capacity() {int cap=getCapacity(); return cap;}

int MyStack::length(){return rear+1;}

int MyStack::pop(){int out=get(rear); rear--; return out;}

 

int main(void){

MyStack mStack(100);

        int n;

        cout << "스택에 삽입할 5개의 정수를 입력하라>> ";

        for(int i=0;i<5;i++){

               cin >> n;

               mStack.push(n); //큐에 삽입

        }

        cout<<"스택 용량: " <<mStack.capacity()<<", 스택 크기:"<<mStack.length()<<endl;

        cout<<"스택의 모든 원소를 팝하여 출력한다>> ";

        while(mStack.length()!=0){

               cout<<mStack.pop()<<' '; //큐에서 제거하여 출력

        }

        cout<<endl<<"큐의 현재 크기 : "<<mStack.length()<<endl;

        return 0;

}

 

<결과창>

  

 

반응형

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

Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Statistics class  (0) 2017.12.25
반응형

8.5> BaseArray를 상속받아 큐처럼 작동하는 MyQueue 클래스를 작성하라. MyQueue를 활용하는 사례는 다음과 같다.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseArray{

private:

        int capacity;//배열의 크기

        int *mem;//정수 배열을 만들기 위한 메모리의 포인터

protected:

        BaseArray(int capacity=100){ //디폴트 매개변수 100

               this->capacity=capacity;

               mem=new int[capacity]; //캐패시티 크기로 동적 배열 형성

        }

        ~BaseArray(){delete []mem;} //동적 메모리 힙으로 반환

        void put(int index, int val){mem[index]=val;} //인덱스에 매개변수 삽입

        int get(int index){return mem[index];} //해당 인덱스에서 정수 가져옴

        int getCapacity(){return capacity;} //용량 리턴

};

class MyQueue : public BaseArray{

private:

        int rear; //마지막 인덱스

        int front; // 첫번째 인덱스 -1

public:

        MyQueue(int capacity,int front,int rear); // 생성자

        void enqueue(int arg); //마지막에 원소 추가

        int capacity(); //용량

        int length(); //현재 길이

        int dequeue(); //첫번째 원소 리턴

};

MyQueue::MyQueue(int capacity=100,int front=-1,int rear=-1):BaseArray(capacity){

        this->front=front;

        this->rear=rear;

}

void MyQueue::enqueue(int arg){

        rear++;

        put(rear,arg);

}

int MyQueue::capacity(){int cap=getCapacity(); return cap;}

int MyQueue::length(){

        return rear-front;

}

int MyQueue::dequeue(){

        int out=get(front+1);

        front++;

        return out;

        }

int main(void){

        MyQueue mQ(100);

        int n;

        cout << "큐에 삽입할 5개의 정수를 입력하라>> ";

        for(int i=0;i<5;i++){

               cin >> n;

               mQ.enqueue(n); //큐에 삽입

        }

        cout<<"큐의 용량: " <<mQ.capacity()<<", 큐의 크기:"<<mQ.length()<<endl;

        cout<<"큐의 원소를 순서대로 제거하여 출력한다>> ";

        while(mQ.length()!=0){

               cout<<mQ.dequeue()<<' '; //큐에서 제거하여 출력

        }

        cout<<endl<<"큐의 현재 크기 : "<<mQ.length()<<endl;

        return 0;

}

 

<결과창>

  

                                 


반응형

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

ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Statistics class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
 
using namespace std;
 
namespace yh{
    class test{
    public:
        int test_print();
    };
}
 
int yh::test::test_print(){
    return 3;
}
 
int main(void){
    
    yh::test c;
    cout<<c.test_print()<<endl;
    
    return 0;
}
cs


리턴타입 네임스페이스명::클래스명::함수명(arguments){}


과 같이 해주면 된다.  자바의 솔루션과 비슷한 개념 같은데 디렉토리가 따로 생성되지는 않는 것을 보아


좀 더 저급한 개념인 것 같다. 이것이 발전해서 자바의 패키지가 된 것 같다. (나의 생각)

반응형

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

문자열 문자 랜덤 수정  (0) 2017.11.03
변수와 포인터와 레퍼런스  (0) 2017.10.27
다수의 클래스 연산자  (0) 2017.10.12
Integer 클래스  (0) 2017.10.12
SelectableRandom 클래스  (0) 2017.10.12
반응형

짝수 홀수를 선택할 수 있도록 생성자를 가진 SelectableRandom 클래스를 작성하고 각각 짝수 10, 홀수 10개를 랜덤하게 발생시키는 프로그램을 작성하라.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <cstdlib> //atoi,rand,malloc 등의 메소드가 포함된 라이브러리
#include <ctime> //시간과 관련된 메소드, 상수가 포함된 라이브러리
using namespace std;
 
/*rand()함수만 사용하면 무작위 수가 나오기는 하지만 실행할 때마다 같은 무작위 수가 나온다.
왜냐하면 같은 seed값을 이용하기 때문이다.
따라서 srand를 이용해 프로그램을 시작할 때마다 다른 seed값을 넣어주면 매번 다른 무작위 수가 나올것이다.
time 함수는 매 초 다른 값을 반환하기 때문에 seed로 사용하기가 매우 좋다.*/
 
class SelectableRandom {
public:
    SelectableRandom() {
        srand((unsigned)time(0)); //다른 랜덤수를 발생시키기 위한 seed 설정
    }
    int nexteven() { 
        return ((rand()/2)*2);  //2로나눠서 2를 곱하면 범위 그대로 짝수만 나온다.
    }
    int nextodd() { 
        return ((rand()/2)*2)+1;  //2로나눠서 2를 곱하고 1더하면 범위 그대로 홀수만 나온다.
    }
    int nextevenInRange(int a,int b) {
        return (((rand() % (b - a + 1)) + a)/2)*2//범위 짝수
        
    }
    int nextoddInRange(int a,int b) {
        return ((((rand() % (b - a + 1)) + a)/2)*2)+1;    //범위 홀수
    }
};
 
int main(void) {
    SelectableRandom r; //SelectableRandom 클래스의 객체 r
    int i;
    cout << "-- 0에서 " << RAND_MAX << "까지의 짝수 랜덤 정수 10개--" << endl//RAND_MAX=32767 상수
    for (i = 0; i < 10; i++) {
        cout << r.nexteven() << " ";  //10개 랜덤 짝수 정수 출력
    }
    cout << "\n\n";
    cout << "-- 2에서 " <<  "10까지의 홀수 랜덤 정수 10개--" << endl;
    for (i = 0; i < 10; i++) {
        cout << r.nextoddInRange(2,9<< " ";  //범위 내 10개 랜덤 홀수 정수 출력
    }
    cout << endl;
    return 0;
}
 
cs




반응형

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

다수의 클래스 연산자  (0) 2017.10.12
Integer 클래스  (0) 2017.10.12
EvenRandom 클래스  (0) 2017.10.12
Oval (사각형에 내접하는 타원) 클래스  (0) 2017.09.21
랜덤 수 출력  (0) 2017.09.16
반응형

문제 3번을 참고하여 짝수 정수만 랜덤하게 발생시키는 EvenRandom 클래스를 작성하고 EvenRandom 클래스를 이용하여 10개의 짝수를 랜덤하게 출력하는 프로그램을 완성하라. 0도 짝수로 처리한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cstdlib> //atoi,rand,malloc 등의 메소드가 포함된 라이브러리
#include <ctime> //시간과 관련된 메소드, 상수가 포함된 라이브러리
using namespace std;
 
/*rand()함수만 사용하면 무작위 수가 나오기는 하지만 실행할 때마다 같은 무작위 수가 나온다.
왜냐하면 같은 seed값을 이용하기 때문이다.
따라서 srand를 이용해 프로그램을 시작할 때마다 다른 seed값을 넣어주면 매번 다른 무작위 수가 나올것이다.
time 함수는 매 초 다른 값을 반환하기 때문에 seed로 사용하기가 매우 좋다.*/
 
class EvenRandom {
public:
    EvenRandom() {
        srand((unsigned)time(0)); //다른 랜덤수를 발생시키기 위한 seed 설정
    }
    int next() { //rand()함수는 0~32767 사이 무작위 정수 리턴
        return (rand()/2)*2// rand()의 리턴 밸류는 integer 형이다. 따라서 2로 나눴을 때 무조건정수가 나온다.
    //어떤 정수든 (홀수든 짝수든) 2를 곱하면 짝수가 된다. 그리고 반토막 난 범위도 복원된다.
    }
    int nextInRange(int a,int b) {
        return (((rand() % (b - a + 1)) + a)/2)*2//a이상 b미만 랜덤 정수를 뽑는 알고리즘에 짝수 sifting 알고리즘을 더한다.
        
    }
};
 
int main(void) {
    EvenRandom r; //EvenRandom 클래스의 객체 r
    int i;
    cout << "-- 0에서 " << RAND_MAX << "까지의 랜덤 정수 10개--" << endl//RAND_MAX=32767 상수
    for (i = 0; i < 10; i++) {
        cout << r.next() << " ";  //10개 랜덤 정수 출력
    }
    cout << "\n\n";
    cout << "-- 2에서 " <<  "10까지의 랜덤 정수 10개--" << endl;
    for (i = 0; i < 10; i++) {
        cout << r.nextInRange(2,10<< " ";  //범위 내 10개 랜덤 정수 출력
    }
    cout << endl;
    return 0;
}
 
cs



반응형

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

Integer 클래스  (0) 2017.10.12
SelectableRandom 클래스  (0) 2017.10.12
Oval (사각형에 내접하는 타원) 클래스  (0) 2017.09.21
랜덤 수 출력  (0) 2017.09.16
별 출력  (0) 2017.09.09
반응형

Oval 클래스는 주어진 사각형에 내접하는 타원을 추상화한 클래스이다. Oval 클래스의 멤버는 모두 다음과같다. Oval 클래스를 선언부와 구현부로 나누어 작성하라. 

1. 정수값의 사각형 너비와 높이를 가지는 width, height 변수 멤버 

2. 너비와 높이 값이 매개 변수로 받는 생성자 

3. 너비와 높이를 1로 촉기화하는 매개 변수 없는 생성자 

4. Width와 height를 출력하는 소멸자 

5. 타원의 너비를 리턴하는 getWidth() 함수멤버 

6. 타원의 높이를 리턴하는 getHeight() 함수멤버

7. 타원의 너비와 높이를 변경하는 set(int w,int h) 함수멤버

8. 타원의 너비와 높이를 화면에 출력하는 show()함수 멤버


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
 
using namespace std;
 
class Oval {
private:
    int width;
    int height;
public:
    Oval(int a, int b) {
        width = a;
        height = b;
    }
    Oval() {
        width = 1;
        height = 1;
    }
    ~Oval() {
        cout <<"Oval 소멸 "<< "width : " << width << " " << "height : " << height << endl;
    }
    int getWidth() {
        return width;
    }
    int getHeight() {  //클래스 선언부에 직접 구현된 함수는 인라인 함수가 된다.
        return height;
    }
    void set(int w, int h);
    void show();
    
};
 
void Oval::set(int w, int h) { //width와 height를 셋 해주는 함수
    width = w;
    height = h;
}
void Oval::show() {  //width 와 height 출력 함수
    cout << "width : " << width << " " << "height : " << height << endl;
}
 
int main(void) {
    Oval a;  //Oval 형 객체 a 생성자 매개변수 없는 것이 호출되어 1,1 로 width와 height 초기화
    Oval b(34); //Oval 형 객체 b 3,4 로 width와 height 초기화
    a.set(1020); //a의 height와 width 를 10,20으로 셋
    a.show(); //출력
    cout << b.getWidth() << "," << b.getHeight() << endl//get 함수로 b의 width와 height 출력 직접 접근은 불가(private이라서)
 
    return 0;
    }
cs




반응형

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

SelectableRandom 클래스  (0) 2017.10.12
EvenRandom 클래스  (0) 2017.10.12
랜덤 수 출력  (0) 2017.09.16
별 출력  (0) 2017.09.09
1부터 10까지 더하기  (0) 2017.09.09

+ Recent posts