반응형

1.1 스칼라 및 벡터

스칼라(scalar) : 크기만 갖는다. 값이 단 하나의 실수로 표시될 수 있음 (온도, 질량, 밀도, 압력, 전압..)

벡터(vector) :  크기와 방향을 전부 갖는다. n차원에서 정의 가능 하다. (힘, 가속도..)

장(계, field) : 임의의 원점에서 공간 내의 점을 연결하는 vector 의 함수 (지구자계 내의 나침반 자침에 작용하는 힘) - 반드시 공간영역과 관련을 가져야 한다. 

    *스칼라계 : 물컵 속 각 점의 온도 분포 

    *벡터계 : 중력계, 자계, 전계 (electric field)

 

1.2 벡터대수

교환법칙 (commutative law) : A+B=B+A

결합법칙 (associative law) : A+(B+C)=(A+B)+C

분배법칙 (distributive law, 스칼라와 벡터의 곱) : (a+b)(A+B)=aA+aB+bA+bB

*위 법칙의 전제는 벡터의 작용점이 같다는 것이다. 

 

반응형
반응형

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

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

7.9> 통계를 내는 Statistics 클래스를 만들려고 한다. 데이터는 Statistics 클래스 내부에 int 배열을 동적으로 할당받아 유지한다. 다음과 같은 연산이 잘 이루어지도록 Statistics 클래스와 !, >>, <<, ~ 연산자 함수를 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class Statistics{

private:

        int size; //동적 배열의 사이즈

        int index; //마지막 원소의 인덱스

        int *p; //동적 배열을 가리킬 포인터

public:

        Statistics(int size=5,int index=-1); //기본 사이즈 5, 인덱스 -1(nothing)

        friend bool operator!(Statistics op);

        void operator>>(int &op);

        Statistics& operator<<(int op);

        void operator~();

       

};

Statistics::Statistics(int size,int index){

        this->size=size;

        this->index=index;

        p=new int[size]; //size 크기만큼의 int 동적 배열 할당

}

 

bool operator!(Statistics op){

        if(op.index==-1) //index -1이면 true 반환

               return true;

        else

               return false;

}

void Statistics::operator>>(int &op){ //평균구하는 함수

        int sum=0;

        for(int i=0;i<index+1;i++){sum+=p[i];} //실제 원소 개수는 index+1 (0부터시작하니까)

        op= sum/(index+1); //op 평균값 넣어줌(참조라서 원본 바뀜)

}

Statistics& Statistics::operator<<(int op){

        index++; //인덱스 증가

        if(size<=index){ //인덱스를 하나키웠는데 size 크기 같으면 배열 크기보다 원소가 많은 경우

               int *tmp=new int[size+5]; //하나씩 키우면 자주 없앴다 만들었다 해야하니 5개씩 늘린다.

               for(int i=0;i<size;i++){ //(size+5 하면 p크기가 size라서 오류날 있음)

                       tmp[i]=p[i]; //p 원소를 전부 tmp 복사

               }

               delete []p; //p 가리키는 동적배열 힙에 반환

               p=tmp; //tmp 가리키는 배열을 p 가리키게 (어차피 tmp 사라지므로 깊은 복사 필요 없음)

               size+=5; //size 5 추가

        }

        p[index]=op; //index 오퍼랜드 대입

        return *this; //현재 객체의 참조 리턴(이름)

}

void Statistics::operator~(){ //전부 출력하는 함수

        for(int i=0;i<index+1;i++){ //원소 개수 = index+1

               cout<<p[i]<<" ";

        }

        cout<<endl;

}

 

int main(void){

        Statistics stat;

        if(!stat) cout<<"현재 통계 데이타가 없습니다."<<endl;

        int x[5];

        cout <<"5 개의 정수를 입력하라>>";

        for(int i=0;i<5;i++) cin >> x[i]; //x[i] 정수 입력

        for(int i=0;i<5;i++) stat << x[i]; //x[i] 값을 통계 객체에 삽입한다.

        stat << 100 << 200; //100, 200 통계 객체에 삽입한다.

        ~stat; //통계 데이타를 모두 출력한다.

 

        int avg;

        stat>>avg; //통계 객체로부터 평균을 받는다.

        cout<<"avg="<<avg<<endl; //평균을 출력한다.

        return 0;

}

 

<결과창>

               

                    


반응형

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

MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
Circle class  (0) 2017.12.25
Matrix class 활용, 연산자 오버로딩  (0) 2017.12.25
반응형

7.8> 문제 7번의 Circle 객체에 대해 다음 연산이 가능하도록 연산자를 구현하라.

<코드>

#include <iostream>

 

using namespace std;

 

class Circle{

private:

        int radius;

public:

        Circle(int radius=0){this->radius=radius;}

        void show(){cout<<"radius = "<<radius<<" "<<endl;}

        friend Circle operator++(Circle &c);

        friend Circle operator++(Circle &c,int a);

        friend Circle operator+(int a,Circle c);

};

 

Circle operator++(Circle &c){ //전위 증가

        c.radius++;

        return c;

 

}

Circle operator++(Circle &c,int a){ //후위 증가

        Circle tmp=c;

        c.radius++;

        return tmp;

}

 

Circle operator+(int a,Circle c){ // 정수+객체 오퍼레이터

        Circle tmp;

        tmp.radius=a+c.radius;

        return tmp;

}

 

int main(void){

        Circle a(5), b(4);

        b=1+a;

        a.show();

        b.show();

        return 0;

}

 

<결과창>



반응형

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

Stack class  (0) 2017.12.25
Statistics class  (0) 2017.12.25
Circle class  (0) 2017.12.25
Matrix class 활용, 연산자 오버로딩  (0) 2017.12.25
Matrix class  (0) 2017.12.25
반응형

7.7> 원을 추상화한 Circle 클래스는 간단히 아래와 같다. 다음 연산이 가능하도록 연산자를 프렌드 함수로 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class Circle{

private:

        int radius;

public:

        Circle(int radius=0){this->radius=radius;}

        void show(){cout<<"radius = "<<radius<<" "<<endl;}

        friend Circle operator++(Circle &c);

        friend Circle operator++(Circle &c,int a);

 

};

 

Circle operator++(Circle &c){ //전위 증가

        c.radius++;

        return c;

 

}

Circle operator++(Circle &c,int a){ //후위 증가

        Circle tmp=c;

        c.radius++;

        return tmp;

}

 

int main(void){

        Circle a(5), b(4);

        ++a; //증가 리턴

        b=a++; //대입 증가

        a.show();

        b.show();

        return 0;

}

 

<결과창>



반응형

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

Statistics class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
Matrix class 활용, 연산자 오버로딩  (0) 2017.12.25
Matrix class  (0) 2017.12.25
Trace 클래스  (0) 2017.12.25
반응형

7.6> 2차원 행렬을 추상화한 Matrix 클래스를 활용하는 다음 코드가 있다.

(1) <<. >> 연산자 함수를 Matrix의 멤버 함수로 구현하라.

<코드1>

#include <iostream>

 

using namespace std;

 

class Matrix{

private:

        int mat[4]; //인트형 배열 크기는 4

public:

        Matrix(int x0=0,int x1=0,int x2=0,int x3=0); // 디폴트 매개변수는 0

        void show();

        void operator>>(int *x);

        void operator<<(int *y);

};

Matrix::Matrix(int x0,int x1, int x2, int x3){

        mat[0]=x0;     mat[1]=x1; //멤버 인트 배열을 매개변수로 차례로 초기화

        mat[2]=x2;     mat[3]=x3;

}

void Matrix::show(){ //출력함수

        cout<<"Matrix = {";

        for(int i=0;i<4;i++) {cout<<" "<<mat[i];}

        cout<<" }"<<endl;

}

 

void Matrix::operator>>(int *x){ //x 가리키는 배열에 객체 배열 원소 차례로 대입

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

               x[i]=(this->mat)[i];

        }

}

void Matrix::operator<<(int *y){ //객체 배열에 y 가리키는 배열 원소 차례로 대입

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

               (this->mat)[i]=y[i];

        }

}

int main(void){

 

        Matrix a(4,3,2,1), b;

        int x[4], y[4]={1,2,3,4}; //2차원 행렬의 4 원소

        a>>x; //a 원소를 배열 x 복사, x[] {4,3,2,1}

        b<<y; // 배열 y 원소 값을 b 원소에 설정

        for(int i=0;i<4;i++) cout<<x[i]<<" "; //x[]출력

        cout<<endl;

        b.show();

        return 0;

}

(2) <<. >> 연산자 함수를 Matrix의 프렌드 함수로 구현하라.

<코드2>

#include <iostream>

 

using namespace std;

 

class Matrix{

private:

        int mat[4]; //인트형 배열 크기는 4

public:

        Matrix(int x0=0,int x1=0,int x2=0,int x3=0); // 디폴트 매개변수는 0

        void show();

        friend void operator>>(Matrix op1,int *op2);

        friend void operator<<(Matrix &op1,int *op2);

};

Matrix::Matrix(int x0,int x1, int x2, int x3){

        mat[0]=x0;     mat[1]=x1; //멤버 인트 배열을 매개변수로 차례로 초기화

        mat[2]=x2;     mat[3]=x3;

}

void Matrix::show(){ //출력함수

        cout<<"Matrix = {";

        for(int i=0;i<4;i++) {cout<<" "<<mat[i];}

        cout<<" }"<<endl;

}

void operator>>(Matrix op1,int *op2){ //객체의 값을 배열에 대입

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

               op2[i]=(op1.mat)[i];

        }

}

void operator<<(Matrix &op1,int *op2){ //배열의 값을 객체에 대입

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

               (op1.mat)[i]=op2[i];

        }

}

 

 

int main(void){

 

        Matrix a(4,3,2,1), b;

        int x[4], y[4]={1,2,3,4}; //2차원 행렬의 4 원소

        a>>x; //a 원소를 배열 x 복사, x[] {4,3,2,1}

        b<<y; // 배열 y 원소 값을 b 원소에 설정

        for(int i=0;i<4;i++) cout<<x[i]<<" "; //x[]출력

        cout<<endl;

        b.show();

        return 0;

}

 

<결과창>

   

                                

 

반응형

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

Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
Circle class  (0) 2017.12.25
Matrix class  (0) 2017.12.25
Trace 클래스  (0) 2017.12.25
Random 클래스  (0) 2017.12.25
반응형

7.5> 2차원 행렬을 추상화한 Matrix 클래스를 작성하고, show() 멤버 함수와 다음 연산이 가능하도록 연산자를 모두 구현하라.

(1) 연산자 함수를 Matrix의 멤버 함수로 구현하라.

<코드1>

#include <iostream>

 

using namespace std;

 

class Matrix{

private:

        int mat[4]; //인트형 어레이 mat 크기 4

public:

        Matrix(int x0=0,int x1=0,int x2=0, int x3=0);// 디폴트 매개변수는 0

        void show();

        Matrix operator+(Matrix op);

        Matrix operator+=(Matrix op);

        bool operator==(Matrix op);

};

Matrix::Matrix(int x0,int x1,int x2, int x3){ //생성자, 매개변수를 원소에 대입

        mat[0]=x0;     mat[1]=x1;

        mat[2]=x2;     mat[3]=x3;

}

void Matrix::show(){ //출력함수

        cout<<"Matrix = {";

        for(int i=0;i<4;i++) {cout<<" "<<mat[i];}

        cout<<" }"<<endl;

}

 

Matrix Matrix::operator+(Matrix op){ //+연산자 오버로딩, 각원소를 전부 더해서 객체 리턴

        Matrix tmp;

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

               (tmp.mat)[i]=(this->mat)[i]+(op.mat)[i];

        }

        return tmp;

}

 

Matrix Matrix::operator+=(Matrix op){ //+=연산자 오버로딩 객체자신과 op 원소를 각각더해서

        for(int i=0;i<4;i++){                 //자기 자신에 대입하고 객체자신 리턴

               (this->mat)[i]=(this->mat)[i]+(op.mat)[i];

        }

        return *this;

}

 

bool Matrix::operator==(Matrix op){ //==오퍼레이터 오버로딩

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

               if((this->mat)[i]!=(op.mat)[i]) return false; //같은 인덱스 원소 비교해서 다르면 바로 false 리턴

        }

        return true; //다맞으면 true 리턴

}

int main(void){

        Matrix a(1,2,3,4), b(2,3,4,5), c;

        c=a+b; //a+b값을 c 대입

        a+=b; //a+b값을 a 대입

        a.show(); b.show(); c.show();

        if(a==c) //ac 같으면..

               cout<<"a and c are the same" <<endl;

 

        return 0;

}

 

(2) 연산자 함수를 Matrix의 프렌드 함수로 구현하라.

<코드2>

#include <iostream>

 

using namespace std;

class Matrix{

private:

        int mat[4]; //인트형 어레이 mat 크기 4

public:

        Matrix(int x0=0,int x1=0,int x2=0, int x3=0);// 디폴트 매개변수는 0

        void show();

        friend Matrix operator+(Matrix op1,Matrix op2);

        friend Matrix operator+=(Matrix &op1,Matrix op2);

        friend bool operator==(Matrix op1,Matrix op2);

};

Matrix::Matrix(int x0,int x1,int x2, int x3){ //생성자, 매개변수를 원소에 대입

        mat[0]=x0;     mat[1]=x1;

        mat[2]=x2;     mat[3]=x3;

}

void Matrix::show(){ //출력함수

        cout<<"Matrix = {";

        for(int i=0;i<4;i++) {cout<<" "<<mat[i];}

        cout<<" }"<<endl;

}

Matrix operator+(Matrix op1,Matrix op2){  // 원소를 더해 나온 행렬을 리턴

        Matrix tmp;

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

               (tmp.mat)[i]=(op1.mat)[i]+(op2.mat)[i];

        }

        return tmp;

}

Matrix operator+=(Matrix &op1,Matrix op2){ //레퍼런스op1 쓰는 이유는 op1 바뀌어야해서

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

               (op1.mat)[i]=(op1.mat)[i]+(op2.mat)[i]; //배열의 같은 인덱스 값을 더해서 op1 인덱스원소에 대입

        }

        return op1;

}

bool operator==(Matrix op1,Matrix op2){

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

               if((op1.mat)[i]!=(op2.mat)[i]) return false; //같은 인덱스 원소 비교해서 다르면 바로 false 리턴

        }

        return true; //다맞으면 true 리턴

}

 

 

int main(void){

        Matrix a(1,2,3,4), b(2,3,4,5), c;

        c=a+b; //a+b값을 c 대입

        a+=b; //a+b값을 a 대입

        a.show(); b.show(); c.show();

        if(a==c) //ac 같으면..

               cout<<"a and c are the same" <<endl;

 

        return 0;

}

 

<결과창>

       

                            

 

반응형

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

Circle class  (0) 2017.12.25
Matrix class 활용, 연산자 오버로딩  (0) 2017.12.25
Trace 클래스  (0) 2017.12.25
Random 클래스  (0) 2017.12.25
배열 빼기  (0) 2017.12.25
반응형

6.8> 디버깅에 필요한 정보를 저장하는 Trace 클래스를 만들어보자. 저자의 경험에 의하면 멀티태스크 프로그램을 개발하거나 특별한 환경에서 작업할 때, Visual Studio의 디버거와 같은 소스 레벨 디버거를 사용하지 못하는 경우가 더러 있었고, 이때 실행 도중 정보를 저장하기 위해 Trace 클래스를 만들어 사용하였다. Trace 클래스를 활용하는 다음 프로그램과 결과를 참고하여 Trace 클래스를 작성하고 전체 프로그램을 완성하라. 디버깅 정보는 100개로 제한한다.

<코드>

#include <iostream>

#include <string>

using namespace std;

 

class Trace{

private:

        static int num; //카운터로 사용할 변수

        static string func[100]; //함수 이름이 들어갈 스트링 배열

        static string debug[100]; //디버깅 내용이 들어갈 스트링 배열

public:

        static void put(string funcname,string s);

        static void print(string cmp);

        static void print();

};

int Trace::num=0; //스태틱 멤버 변수는 클래스 밖에서 메모리를 할당하는 전역 변수 선언문을 작성해야 한다.

string Trace::func[100];

string Trace::debug[100];

 

void Trace::put(string funcname,string s){ //num 해당하는 index 함수 이름과 디버깅 내용을 넣어준다.

        func[num]=funcname;

        debug[num]=s;

        num++; //카운터 하나 증가

}

void Trace::print(string cmp){

        cout<<cmp<<"태그의 Trace 정보를출력합니다.-----"<<endl;

        for(int i=0;i<num;i++){ //카운터만큼 반복한다.

               if(func[i]==cmp) //함수이름과 cmp 같으면 함수 이름과 디버깅 내용 출력

                       cout<<func[i]<<" : "<<debug[i]<<endl;

        }

}

void Trace::print(){

        cout<<"----모든 Trace 정보를출력합니다.-----"<<endl;

        for(int i=0;i<num;i++){ //카운터 만큼 반복

                       cout<<func[i]<<" : "<<debug[i]<<endl;

        }

}

 

void f(){ //a+b c 대입, 자취 2 생성

        int a,b,c;

        cout<<" 개의 정수를 입력하세요>>";

        cin>>a>>b; //a,b 입력 받아서

        Trace::put("f()", "정수를 입력 받았음");

        c=a+b; //c 대입후

        Trace::put("f()", " 계산");

        cout << "합은 " <<c<<endl; //출력

}

 

int main(void){

        Trace::put("main()", "프로그램 시작합니다");

        f();

        Trace::put("main()", "종료");

        Trace::print("f()");

        Trace::print();

        return 0;

}

<결과창>

        

                           


반응형

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

Matrix class 활용, 연산자 오버로딩  (0) 2017.12.25
Matrix class  (0) 2017.12.25
Random 클래스  (0) 2017.12.25
배열 빼기  (0) 2017.12.25
동일한 크기의 배열  (0) 2017.12.25
반응형

6.7> 다음과 같은 static 멤버를 가진 Random 클래스를 완성하라(Open Challenge 힌트참고). 그리고 Random 클래스를 이용하여 다음과 같이 랜덤한 값을 출력하는 main() 함수도 작성하라. Main()에서 Random 클래스의 seed() 함수를 활용하라.

<코드>

#include <iostream>

#include <ctime> //time 함수 사용 위함

#include <stdlib.h> //rand, srand, RAND_MAX 사용 위함

 

using namespace std;

 

class Random{

public:

        static void seed(){srand((unsigned)time(0));} //현재 시간으로 랜덤 시드 초기화

        static int nextInt(int min=0, int max=32767); //디폴트 매개변수 min=0, max=32767(RAND_MAX)

        static char nextAlphabet();

        static double nextDouble();

};

int Random::nextInt(int min, int max){ //함수 구현시 디폴트 매개 변수 다시 입력하지 않는다.

        return rand()%(max-min+1)+min; //min 이상 max 이하 랜덤 출력

}

char Random::nextAlphabet(){ //'A'=65 'Z'=90 'a'=97'z'=122

        if(rand()%2) //1이면 대문자

        return rand()%(26)+65; //대문자 리턴

        else //아니면 소문자

        return rand()%(26)+97; //소문자 리턴

}

double Random::nextDouble(){ //실수로 강제형변환한 rand 최대 나올수 있는 수를 실수로 형변환 것으로 나눠준다

        return (double)rand()/(double)RAND_MAX; //RAND_MAX rand함수가 반환하는 가장 (32767)

}

 

int main(void){

        int i;

        Random::seed(); //시드 초기화

        cout<<"1에서 100까지 랜덤한 정수 10개를 출력합니다."<<endl;

        for(i=0;i<10;i++){cout<<Random::nextInt(1,100)<<" ";}

        cout<<endl;

        cout<<"알파벳을 랜덤하게 10개를 출력합니다."<<endl;

        for(i=0;i<10;i++){cout<<Random::nextAlphabet()<<" ";}

        cout<<endl;

        cout<<"랜덤한 실수를 10 출력합니다."<<endl;

        for(i=0;i<10;i++){cout<<Random::nextDouble()<<" ";}

        cout<<endl;

 

        return 0;

}

<결과창>

 

                                  


반응형

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

Matrix class  (0) 2017.12.25
Trace 클래스  (0) 2017.12.25
배열 빼기  (0) 2017.12.25
동일한 크기의 배열  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
반응형

6.6> 동일한 크기의 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility2 클래스를 만들고 이 클래스를 이용하여 아래 결과와 같이 출력하도록 프로그램을 완성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class ArrayUtility2{

public:

        static int* concat(int s1[], int s2[], int size);

        //s1 s2 연결한 새로운 배열을 동적 생성하고 포인터 리턴

        static int* remove(int s1[], int s2[], int size, int& retSize);

        //s1에서 s2 있는 숫자를 모두 삭제한 새로운 배열을 동적 생성하여 리턴, 리턴하는

        //배열의 크기는 retSize 전달. retSize 0 경우 NULL 리턴

};

int* ArrayUtility2::concat(int s1[], int s2[], int size){

        int *p=new int[size*2]; //동일한 크기의 배열이므로 size *2 배열을 동적 생성

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

               p[i]=s1[i]; //0~4 인덱스는 s1 초기화

               p[i+size]=s2[i]; //5~9 인덱스는 s2 초기화

        }

        return p; //동적배열을 가리키는 주소 리턴

}

int* ArrayUtility2::remove(int s1[], int s2[], int size, int& retSize){

        int i; int j; int count=0; //빼기 배열 만들 사용할 카운터

        for(i=0;i<size;i++){

               for(j=0;j<size;j++){

                       if(s1[i]==s2[j]){

                              s1[i]=NULL; //s2 원소를 s1 일일이 비교하여 같으면 NULL 교체

                              break; //어차피 1번겹치든 2번겹치든 빼는 것은 한번이기 때문에 break 가능

                       }

               }

        }

        for(i=0;i<size;i++){

               if(s1[i]!=NULL)

                       retSize++; //원소값이 NULL 아니면 retSize 증가

        }

        if(retSize==0) return NULL; //retSize 0이면 NULL포인터 리턴

        int *p=new int[retSize]; //retSize 크기의 인트형 배열 동적 할당

        for(i=0;i<size;i++){

               if(s1[i]!=NULL){ //s1[i] NULL 아니면

                       p[count]=s1[i]; //p[count] 대입

                       count++;

               }

        }

        return p; //동적배열을 가리키는 주소 리턴

}

int main(void){

        int x[5];

        int y[5];

        int i;

        int *conc; //합친 배열 주소 받음

        int *del; // 배열 주소 받음

        int size=sizeof(x)/sizeof(x[0]); //(4*5)/4=5

        int retSize=0; //초기화 안하고 참조에 쓰면 오류생김

        cout<<"정수를 5 입력하라. 배열 x 삽입한다>>";

        for(i=0;i<5;i++){cin>>x[i];} //배열 입력

        cout<<"정수를 5 입력하라. 배열 y 삽입한다>>";

        for(i=0;i<5;i++){cin>>y[i];}

        conc=ArrayUtility2::concat(x,y,size); //합친 배열

        for(i=0;i<size*2;i++){cout<<conc[i]<<" ";} //출력

        cout<<endl;

        del=ArrayUtility2::remove(x,y,size,retSize); // 배열

        cout<<"배열 x[]에서 y[] 결과를 출력한다. 개수는 "<<retSize <<endl;

        for(i=0;i<retSize;i++){cout<<del[i]<<" ";} //출력

        cout<<endl;

        return 0;

}

 

<결과창>




반응형

+ Recent posts