반응형

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;

}

 

<결과창>




반응형
반응형

6.5> 동일한 크기로 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility 클래스를 만들어라.

<코드>

#include <iostream>

 

using namespace std;

 

class ArrayUtility{

public:

        static void intToDouble(int source[], double dest[], int size);

        //int[] double[] 변환

        static void doubleToInt(double source[], int dest[], int size);

        //double[] int[] 변환

};

void ArrayUtility::intToDouble(int source[], double dest[], int size){

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

               dest[i]=(double)source[i]; //강제 형변환

        }

}

void ArrayUtility::doubleToInt(double source[], int dest[], int size){

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

               dest[i]=(int)source[i]; //강제 형변환, 소수점은 날아간다.

        }

}

int main(void){

        int x[]={1,2,3,4,5};

        double y[5];

        double z[]={9.9,8.8,7.7,6.6,5.6};

 

        ArrayUtility::intToDouble(x,y,5); // x[]-> y[]

        for(int i=0;i<5;i++) cout << y[i] << ' ';

        cout << endl;

        ArrayUtility::doubleToInt(z,x,5); //z[]->x[]

        for(int i=0;i<5;i++) cout << x[i] << ' ';

        cout << endl;

        return 0;

}


<결과창>



}


반응형

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

Random 클래스  (0) 2017.12.25
배열 빼기  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
반응형

6.4> 다음 클래스에 중복된 생성자를 디폴트 매개 변수를 가진 하나의 생성자로 작성하고 테스트 프로그램을 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class MyVector{

private:

        int* mem;

        int size;

public:

        MyVector(int n,int val);

        ~MyVector(){delete []mem;} //동적 배열이 할당받은 메모리를 힙에 반환

        void printVector();

};

 

MyVector::MyVector(int n=100,int val=0){

        //n실인자가 입력되지 않으면 100대입,val 실인자 없으면 0대입

        mem=new int[n]; //n크기의 인트형 동적 배열

        size=n;

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

               mem[i]=val; //동적 배열의 모든 원소를 val 초기화해준다.

}

void MyVector::printVector(){ //10개씩 끊어서 출력

        int moc=size/10; //

        int namuji=size%10; //나머지

        for(int j=0;j<moc;j++){

        for(int i=0;i<10;i++){cout<<mem[i];} //몫에 해당하는만큼 출력

        cout<<endl;

        }

        for(int k=0;k<namuji;k++) //나머지에 해당하는 만큼 출력

               {cout<<mem[k];}

        cout<<endl;

}

int main(void){

        MyVector m1; //사이즈 100, 원소는 0

        MyVector m2(53); //사이즈 53, 원소는 0

        MyVector m3(27,3); //사이즈 27, 원소는 3

        m1.printVector();

        m2.printVector();

        m3.printVector();

        return 0;

}

<결과창>

                              

 

반응형

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

배열 빼기  (0) 2017.12.25
동일한 크기의 배열  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
반응형

6.2> Person 클래스의 객체를 생성하는 main() 함수는 다음과 같다.

(1) 생성자를 중복 작성하고 프로그램을 완성하라.

<코드1>

#include <iostream>

#include <string>

 

using namespace std;

 

class Person{

private:

        int id;

        double weight;

        string name;

public:

        void show(){cout<<id<<" "<<weight<<" "<<name<<endl;} //출력함수

        Person();

        Person(int id, string name);

        Person(int id,string name,double weight); //생성자 오버로딩

};

Person::Person(){//매개변수 없는 생성자

        this->id=1;

        this->weight=20.5;

        this->name="Grace";

}

Person::Person(int id, string name){ //매개변수 2개인 생성자

        this->id=id;

        this->weight=20.5;

        this->name=name;

}

 

Person::Person(int id,string name,double weight){ //매개변수 3개인 생성자

        this->id=id;

        this->name=name;

        this->weight=weight;

}

 

int main(void){

        Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);

        grace.show();

        ashley.show();

        helen.show();

        return 0;

}

 

 

(2) 디폴트 매개 변수를 가진 하나의 생성자를 작성하고 프로그램을 완성하라.

<코드2>

#include <iostream>

#include <string>

 

using namespace std;

 

class Person{

private:

        int id;

        double weight;

        string name;

public:

        void show(){cout<<id<<" "<<weight<<" "<<name<<endl;} //출력함수

        Person(int id,string name,double weight);

};

Person::Person(int id=1,string name="Grace",double weight=20.5){ //디폴트매개변수를 가진 생성자

        this->id=id;

        this->name=name;

        this->weight=weight;

        //id 입력이 없으면 1 대입, name 입력이 없으면 "Grace" 대입, weight 입력이 없으면 20.5 대입

}

 

int main(void){

        Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);

        grace.show();

        ashley.show();

        helen.show();

        return 0;

}

 

 

<결과창>

   

    


반응형

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

동일한 크기의 배열  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
모스 부호  (0) 2017.11.09

+ Recent posts