반응형

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.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
반응형
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>
using namespace std;
 
class Power{
    int kick;
    int punch;
public:
    Power(int kick=0int punch=0){
        this->kick=kick; this->punch=punch;
    }
    void show();
    friend Power operator+(int op1, Power op2); //정수+객체를 위하여..
    Power operator+(int op2); //객체+정수를 위하여..
};
void Power::show(){
    cout<<"kick="<<kick<<","<<"punch="<<punch<<endl;
}
Power operator+(int op1,Power op2){
    Power tmp;
    tmp.kick=op1+op2.kick;
    tmp.punch=op1+op2.punch;
    return tmp;
}
Power Power::operator+(int op2){
    Power tmp;
    tmp.kick=this->kick + op2;
    tmp.punch=this->punch +op2;
    return tmp;
}
 
int main(void){
    Power a(3,5), b,c;
    a.show();
    b.show();
    c.show();
    b=2+a;
    c=a+3;
    a.show();
    b.show();
    c.show();
}
cs




연산자 오버로딩을 클래스의 멤버 함수로 정의하는 방법과 외부 함수로 정의한 후 프렌드 선언을 해주는 방법이 있는데

operand(피연산자) 순서의 차이를 보인다. 만약 둘 중 한가지 방법만 쓴다면

프로그램 작성시 operand의 순서를 조심해야겠다.

반응형

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

생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
모스 부호  (0) 2017.11.09
Book 클래스  (1) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
반응형

4.2>. 다음과 같은 멤버를 가지는 직사각형을 표현하는 Rectangle 클래스를 작성하라.

- int 타입의 x1, y1, x2, y2 필드 : 사각형을 구성하는 두 점의 좌표

- 생성자 2: 매개 변수 없는 생성자와 x1, y1, x2, y2의 값을 설정하는 생성자

- void set(int x1, int y1, iny x2, int y2) : x1, y1, x2, y2좌표 설정

- int square() : 사각형 넓이 리턴

- void show() :좌표와 넓이 등 직사각형 정보의 화면 출력

) 사각형의 좌표는 (0,0), (0,0)입니다.

- boolean equals(Rectangle r) : 인자로 전달된 객체 r과 현 객체가 동일한 직사각형이면 true 리턴

 

Rectangle을 이용한 main() 메소드는 다음과 같으며 이 main() 메소드가 잘 작동하도록 하라.

public class RectManager {

             public static void main(String args[]) {

                           Rectangle r = new Rectangle();

                           Rectangle s = new Rectangle(1,1,2,3);

                           r.show();

                           s.show();

                           System.out.println(s.square());

                           r.set(-2,2,-1,4);

                           r.show();

                           System.out.println(r.square());

                          if(r.equals(s))

                                        System.out.println(" 사각형은 같습니다.");

             }

}



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
package HW1_JAVA;
class Rectang{ //Rectang class 선언
        int x1,y1,x2,y2; //int 형 변수 x1,y1,x2,y2 선언
        Rectang(){  //constructor Rectang 아규먼트 없을때
            this.x1=0;  // 객체의 x1,y1,x2,y2에 0 대입
            this.y1=0;
            this.x2=0;
            this.y2=0;}
        Rectang(int x1, int y1, int x2, int y2){
            this.x1=x1;  //객체의 x1,y1,x2,y2에 인자 x1,y1,x2,y2 대입
            this.y1=y1;     //하는 constructor (오버로딩)
            this.x2=x2;
            this.y2=y2;}
        void set(int x1, int y1, int x2, int y2){
            this.x1=x1; //객체의 x1,y1,x2,y2에 인자 x1,y1,x2,y2 대입하는 메소드 set
            this.y1=y1;
            this.x2=x2;
            this.y2=y2;}
        int square(){ //메소드 square 선언
            int length=Math.abs(this.x2-this.x1); //밑변은 x2-x1한 것의 절대값
            int height=Math.abs(this.y2-this.y1); //높이는 y2-y1한 것의 절대값
            return length*height;} //밑변*높이 반환
        void show(){ //메소드 show 선언, 좌표와 밑변 넓이를 화면에 출력해준다. printf를 사용하였다.
            System.out.printf("사각형의 좌표는 (%d,%d),(%d,%d) 입니다.\n",this.x1,this.y1,this.x2,this.y2);
            System.out.printf("사각형의 밑변은 %d, 높이는 %d입니다.\n",Math.abs(this.x2-this.x1),Math.abs(this.y2-this.y1));;
            System.out.printf("사각형의 넓이는 %d입니다.\n",square());}
        boolean equals(Rectang r){ //리턴값 true와 false만 있는 메소드 equals
        if((Math.abs(this.x2-this.x1)==Math.abs(r.x2-r.x1))&&(Math.abs(this.y2-this.y1)==Math.abs(r.y2-r.y1)))
            return true//밑변길이와 높이를 비교해서 둘다 같으면 true 반환
        else //아니면 false 반환
            return false;}}
public class Square {
    public static void main(String[] args) {
        Rectang r = new Rectang();  //인자없는 생성자로 생성한 Rectang의 객체와 레퍼런스 변수 r
        Rectang s = new Rectang(1,1,2,3); //인자를 넣어준 Rectang의 객체와 레퍼런스 변수 s
        r.show(); //r이 가리키는 객체의 show 메소드 호출
        s.show(); //s가 가리키는 객채의 show 메소드 호출
        System.out.println(s.square()); //s가 가리키는 객체의 square 메소드 호출 후 리턴 값 출력
        r.set(-2,2,-1,4); //r이 가리키는 객체의 set 메소드 호출 
        r.show(); //r이 가리키는 객체의 show 메소드 호출
        System.out.println(r.square()); //r이 가리키는 객체의 square 메소드 호출 후 리턴 값 출력
        if(r.equals(s)) //만약 r.equals(s)가 ture를 반환하면(r과 s 비교)
            System.out.println("두 사각형은 같습니다.");  // 해당 스트링 출력
    }}
 
cs




반응형

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

상속 클래스  (0) 2017.06.18
ArrayUtility class  (0) 2017.06.18
돈 단위 나누기  (0) 2017.06.18
2차원 배열  (0) 2017.06.18
정수 오름차순 정렬기  (0) 2017.06.18

+ Recent posts