반응형

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.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

+ Recent posts