반응형

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
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
#include <iostream>
 
using namespace std;
 
class A {
public:
     virtual void print() { cout << "에이" << endl; }
};
class B : public A {
public:
 virtual void print() { cout << "비" << endl; }
};
 
class C : public B {
public:
    virtual void print() { cout << "씨" << endl; }
};
 
/*참고로, 부모 클래스에서 멤버 함수 선언문 앞에 virtual 키워드가 존재한다면,
자식 클래스에서 오버라이딩(재정의, Overriding)한 함수도 저절로 가상 함수로 정의됩니다.
그러나, 소스 코드의 이해를 돕기 위해 자식 클래스에도 virtual를 명시해주어야 하는것이 관례입니다.
이번엔 순수 가상 함수(Pure Virtual Function)란 녀석을 살펴보도록 하겠습니다.
출처: http://blog.eairship.kr/175 [누구나가 다 이해할 수 있는 프로그래밍 첫걸음]*/
 
int main(void) {
 
    A* p;
    A* a = new A();
    a->print(); //a->A
    B* b = new B();
    b->print(); //b->B
    C* c = new C();
    c->print(); //c->C
    c =(C*) b;  
    c->print(); //c->B
    c = (C*)a;
    c->print(); //c->A
    p = a;
    p->print(); //(p=a)->A
    p = b;
    p->print(); //(p=b)->B
    p = c; 
    p->print(); //(p=c)->A
    
 
}
cs



virtual 을 쓰면 중요한 것은 원래 객체가 어떤 타입이냐!!이다.


반응형

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

생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
operator overloading  (0) 2017.11.14
모스 부호  (0) 2017.11.09
Book 클래스  (1) 2017.11.09
반응형

5.4> main() 함수를 다음과 같이 수행할 수 있도록 하기 위한 CPoint 클래스와 CColorPoint 클래스를 작성하고 전체 프로그램을 완성하라. CColorPoint 클래스의 어떤 메소드에서도 System.out.println()을 호출해서는 안 된다. CPoint 클래스는 생성자가 오직 하나뿐이다.


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
package HW1_JAVA;
class CPoint{ //class CPoint 선언
    int a; int b; String s;  //int형 변수 a,b 와 String s 선언
    protected CPoint(int a, int b){ //int a와 int b를 argument 로 갖는 생성자
        this.a=a; this.b=b; this.s=""//this.a에 a대입 this.b에 b 대입 s에 "" 대입(색깔들어갈자리)
    }
    void show(){
        System.out.println("("+a+","+b+")"+s); // a와 b와 s를 출력하는 메소드 show
    } //toString 메소드는 Object 클래스에 속한다. 
    public String toString(){ //메소드 오버라이딩 시 슈퍼 클래스 메소드의 접근지정자보다 접근 범위가 좁아질 수 없다.
        return "("+a+","+b+")"+" 입니다";
    } //toString : println의 인자로 객체의 레퍼런스 변수가 전달되면 해당 인스턴스의 toString 메소드가 호출되면서
    } // 리턴값으로 반환되는 문자열이 나온다.
class CColorPoint extends CPoint{ //CPoint를 상속하는 클래스 CColorPoint
        CColorPoint(int a, int b,String s)
        {
            super(a,b); //CColorPoint의 슈퍼클래스인 CPoint의 생성자 호출
            this.s=s; // this.s에 인자 s 대입
        }
    }
public class PointCl {
    public static void main(String[] args) {
        CPoint a,b; //CPoint 형 클래스를 가리키는 레퍼런스 변수 a,b
        a=new CPoint(2,3); // CPoint 클래스의 객체 생성(인자는 2,3) 레퍼런스 변수는 a
        b=new CColorPoint(3,4,"red"); //업캐스팅된 CColorPoint 클래스의 객체를 가리키는 레퍼런스변수 b
        a.show(); //a.show 메소드 호출
        b.show(); //b.show 메소드 호출
        System.out.println(a); //a 출력인데 a.toString의 리턴값이 출력됨
        System.out.println(b); //b 출력인데 b.toString의 리턴값이 출력됨
    }
}
 
cs




반응형

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

메소드 오버라이딩  (0) 2017.06.18
추상 클래스  (0) 2017.06.18
ArrayUtility class  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18
돈 단위 나누기  (0) 2017.06.18

+ Recent posts