반응형

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

4.9> 다음은 이름과 반지름을 속성으로 가진 Circle 클래스와 이들을 배열로 관리하는 CircleManager 클래스이다. 키보드에서 원의 개수를 입력받고, 그 개수만큼 원의 이름과 반지름을 입력받고, 다음과 같이 실행되도록 main() 함수를 작성하라. Circle, CircleManager 클래스도 완성하라.


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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>
 
using namespace std;
 
class Circle{ 
private:
    int radius;
    string name;
public:
    void setCircle(string name, int radius){ //멤버 name과 radius를 set해줌.
        this->name=name; this->radius=radius;
    }
    double getArea(){return radius*radius*3.14;} //원의 면적 리턴
    string getName(){return name;} //원의 이름 리턴
};
 
class CircleManager{
private:
    Circle *p; //Circle형 포인터 p
    int size;
public:
 
    CircleManager(int size){ //컨스트럭터
        this->size=size
        p=new Circle[size]; //size크기만큼의 Circle형 동적 객체 배열 생성
        int radius; string name;
        for(int i=0;i<size;i++){
            cin.ignore(100,'\n'); //cin은 개행문자를 버퍼에 남겨놓기 때문에 버퍼에서 비워줘야 한다.
                                //그렇지 않으면 다음 루프의 getline이 개행문자 + 입력한 문자열을 받아버린다.
            cout<<"원 "<<i+1<<"의 이름과 반지름 >>";
            getline(cin,name,' '); // space를 delimeter로 설정하여 이름을 받는다.
            cin>>radius;     //radius는 cin으로 받는다.
            p[i].setCircle(name,radius); //Circle을 set 해줌.
        }
    cin.ignore(); //마지막 개행문자 버퍼에서 제거
    }
    ~CircleManager(){delete []p;} //동적 Circle 객체 배열 해당 메모리 힙으로 반환
    void searchByName(){
        string cmp;
        cout<<"검색하고자 하는 원의 이름>> ";
        getline(cin,cmp,'\n'); //cmp를 getline으로 개행문자 나올때까지 받는다.
        for(int i=0;i<(this->size);i++){
            if(cmp==(p[i].getName()))  //cmp와 i번째 동적circle의 name이 같으면
            {cout<<"도넛의 면적은 "<<p[i].getArea()<<endl//i번째 동적circle의 area 반환
            break;}
        }
    }
    void searchByArea(){
        int area;
        cout<<"최소 면적을 정수로 입력하세요>> ";
        cin>>area; //area를 받는다.
        cout<<area<<"보다 큰 원을 검색합니다."<<endl;
        for(int i=0;i<(this->size);i++){ //동적 객체 배열 전부 순회하여 area보다 
            if(p[i].getArea()>area) //p번째 circle 객체의 넓이가 크면 출력
                cout<<p[i].getName()<<"의 면적은 "<<p[i].getArea()<<", ";
        }
        cout<<endl//개행 출력
    }
};
 
int main(void){
    int size;
    cout<<"원의 개수 >> " ; 
    cin>>size//원의 개수 정함
    CircleManager m(size); //CircleManager객체 생성
    m.searchByName(); //Name으로 찾기
    m.searchByArea(); //특정 Area 초과인것 찾기
    
    return 0;
}
 
cs




반응형

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

float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
반응형

4.8> 다음에서 Person은 사람을, Family는 가족을 추상화한 클래스로서 완성되지 않은 클래스이다. 다음 main()이 작동하도록 Person Family 클래스에 필요한 멤버들을 추가하고 코드를 완성하라.


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
48
49
50
51
52
#include <iostream>
#include <string>
 
using namespace std;
 
class Person{ //Person 클래스
private:
    string name; 
public:
    Person(string name){this->name=name;} //객체멤버 name을 매개변수 name으로 초기화
    Person(){} //디폴트 생성자
    string getName(){return name;} // 멤버변수 name 리턴
    void setName(string name){this->name=name;} //멤버변수 name set함수
    
};
 
class Family{ //Family 클래스
private:
    Person *p; //Person형 포인터 p
    int size//int형 변수 size
    string Fname; //string 형 객체 Fname
public:
    Family(string name, int size){
        p=new Person[size]; //size 크기만큼 동적 Person 객체 배열 생성
        setFname(name); //Fname을 name으로 초기화
        this->size=size//멤버변수 size를 매개변수 size로 초기화
    }
    string getFname(){return Fname;} //Fname 리턴
    int getSize(){return size;} //size 리턴
    void setFname(string Fname){this->Fname=Fname;} //멤버변수 Fname을 매개변수 Fname으로 셋
    void setName(int num, string name){ 
        p[num].setName(name); //num에 해당하는 인덱스에 존재하는 동적 person 객체 배열 원소의 name 셋
    }
    void show(){
        cout<<getFname()<<"가족은 다음과 같이 "<<getSize()<<"명 입니다."<<endl//size 리턴받아 출력
        for(int i=0;i<size;i++){  //i가 0에서부터 size보다 작을때까지
            cout<<p[i].getName()<<"\t"//동적 person 객체 배열 원소에서 getName멤버 함수 호출하여 출력후 탭문자 출력
        }
        cout<<endl// 한줄 내리기
    }
    ~Family(){delete []p;} //소멸자는 동적person배열에 할당된 메모리를 힙에 반납한다. 
};
 
int main(void){
    Family *simpson = new Family("Simpson"3);  //Fname "Simpson", size 3으로 초기화된 Family형 동적 객체, 그걸 가리키는 포인터 simpson
    simpson->setName(0"Mr. Simpson"); //simpson이가리키는 객체 안에서원소3개의 person형 동적 객체 배열이 생성되었고 그중 0번 원소 초기화
    simpson->setName(1"Mrs. Simpson"); //1번 원소 초기화
    simpson->setName(2"Bart Simpson"); //2번 원소 초기화
    simpson->show(); //출력 함수
    delete simpson; //동적 메모리 힙으로 반환
}
 
cs



반응형

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

히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
변수와 포인터와 레퍼런스  (0) 2017.10.27
반응형

4.6> 실습 문제 5의 문제를 수정해보자. 사용자로부터 다음과 같이 원의 개수를 입력받고, 원의 개수만큼 반지름을 입력받는 방식으로 수정하라. 원의 개수에 따라 동적으로 배열을 할당받아야 한다.


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
#include <iostream>
 
using namespace std;
 
class Circle{ //Circle 클래스
private:
    int radius; //private 타입 인티저 radius
public:
    void setRadius(int radius);
    double getArea();
};
void Circle::setRadius(int radius){  //radius 셋하는 함수
    this->radius=radius; //this->radius는 클래스의 멤버 변수,radius는 멤버 함수의 매개 변수
}
double Circle::getArea(){ //넓이를 구해주는 멤버 함수 getArea
    return radius*radius*3.14;
}
 
int main(void){
    int n=0// 원의 개수
    int count=0//면적이 100보다 큰 원 개수
    int r; //반지름을 담을 변수
    while(true){ //원의 개수를 1보다 작게 했을 때 생기는 오류를 없애주는 무한루프
    cout<<"원의 개수 >> ";
    cin>>n; //n을 받는다.
        if(n>=1//n이 1보다 크면 무한루프 탈출
            break;
    }
    Circle *p=new Circle[n]; //Circle 객체를 동적으로 n개 생성 해당포인터 p
    for(int i=0;i<n;i++){
        cout<<"원 "<<i+1<<"의 반지름 >> "
        cin>>r;
        p[i].setRadius(r); //p[i]의 radius를 r로 설정해준다
        if(p[i].getArea()>100//p[i]의 넓이가 100보다크면
            count++//카운트를 늘려준다.
    }
    cout<<"면적이 100보다 큰 원은 "<<count<<"개 입니다."<<endl//100보다큰원 출력
    delete []p; //동적 배열 메모리 힙에 반환
}
 
cs




반응형
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
 
using namespace std;
 
namespace yh{
    class test{
    public:
        int test_print();
    };
}
 
int yh::test::test_print(){
    return 3;
}
 
int main(void){
    
    yh::test c;
    cout<<c.test_print()<<endl;
    
    return 0;
}
cs


리턴타입 네임스페이스명::클래스명::함수명(arguments){}


과 같이 해주면 된다.  자바의 솔루션과 비슷한 개념 같은데 디렉토리가 따로 생성되지는 않는 것을 보아


좀 더 저급한 개념인 것 같다. 이것이 발전해서 자바의 패키지가 된 것 같다. (나의 생각)

반응형

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

문자열 문자 랜덤 수정  (0) 2017.11.03
변수와 포인터와 레퍼런스  (0) 2017.10.27
다수의 클래스 연산자  (0) 2017.10.12
Integer 클래스  (0) 2017.10.12
SelectableRandom 클래스  (0) 2017.10.12
반응형

다수의 클래스를 선언하고 활용하는 간단한 문제이다. 더하기(+), 빼기(-), 곱하기(*), 나누기(/)를 수행하는 4개의 클래스 Add, Sub, Mul, Div 를 만들고자 한다. 이들은 모두 공통으로 다음 멤버를 가진다. Int 타입 변수 a,b : 피연산자 void setValue(int x, int y)함수 : 매개 변수 x,y를 멤버 a,b에 복사 int calculate() 함수 : 연산을 실행하고 결과 리턴 main()함수는 Add, Sub, Mul, Div 클래스 타입의 객체 a, s, m, d를 생성하고 ,아래와 같이 키보드로부터 두 개의 정수와 연산자를 입력받고 a, s, m, d 객체 중에서 연산을 처리할 객체의 setValue() 함수를 호출한 후 calculate()를 호출하여 결과를 화면에 출력한다. 프로그램은 무한 루프를 돈다




< cpp 파일에 전부 넣은 것>

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
using namespace std;
/*각 클래스의 함수들을 직접 구현하는 구현부 cpp파일*/
class Add{
private:
    int a,b;  //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y); // 인자 대입
    int calculate(); //계산
};
class Sub{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
class Mul{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
class Div{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
void Add::setValue(int x,int y){ //값 지정 x를 a에, y를 b에 대입한다.
    a=x;
    b=y;
}
int Add::calculate(){ //더하기 연산
    return a+b;
}
void Sub::setValue(int x,int y){
    a=x;
    b=y;
}
int Sub::calculate(){ //빼기 연산
    return a-b;
}
void Mul::setValue(int x,int y){
    a=x;
    b=y;
}
int Mul::calculate(){ //곱하기 연산
    return a*b;
}
void Div::setValue(int x,int y){ 
    a=x;
    b=y;
}
int Div::calculate(){//나누기 연산
    return a/b;
}
int main(void){
    while(1){
        int x;
        int y;
        char opr; //operator를 구별하기 위한 대입용 캐릭터형 변수
        Add a; Sub s; Mul m; Div d; //각 클래스 객체 생성
        cout<<"두 정수와 연산자를 입력하세요>>";
        cin>>x>>y>>opr;
        if(opr=='+'){ //opr이 +면
            a.setValue(x,y); //operand 값 set 해주고
            cout<<a.calculate()<<endl//계산값 출력
        }
        else if(opr=='-'){ //opr이 -면
            s.setValue(x,y);
            cout<<s.calculate()<<endl;
        }
        else if(opr=='*'){ //opr이 *면
            m.setValue(x,y);
            cout<<m.calculate()<<endl;
        }
        else if(opr=='/'){ //opr이 /면
            d.setValue(x,y);
            cout<<d.calculate()<<endl;
        }
    }
    return 0;
}
 
cs

<코드-헤더파일 Calcuator.h>

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
#ifndef CALC_H //헤더 파일 중복 include 방지용
#define CALC_H
 
class Add{
private:
    int a,b;  //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y); // 인자 대입
    int calculate(); //계산
};
class Sub{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
class Mul{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
class Div{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
#endif
 
cs

<코드-클래스cpp파일 Calculatop.cpp>


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
#include "Calculator.h" //선언부 include
#include <iostream>
using namespace std;
/*각 클래스의 함수들을 직접 구현하는 구현부 cpp파일*/
 
void Add::setValue(int x,int y){ //값 지정 x를 a에, y를 b에 대입한다.
    a=x;
    b=y;
}
int Add::calculate(){ //더하기 연산
    return a+b;
}
void Sub::setValue(int x,int y){
    a=x;
    b=y;
}
int Sub::calculate(){ //빼기 연산
    return a-b;
}
void Mul::setValue(int x,int y){
    a=x;
    b=y;
}
int Mul::calculate(){ //곱하기 연산
    return a*b;
}
void Div::setValue(int x,int y){ 
    a=x;
    b=y;
}
int Div::calculate(){//나누기 연산
    return a/b;
}
 
cs



<코드-메인cpp파일 main.cpp>

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
#include <iostream>
#include "Calculator.h" //calculator 내에 클래스 사용 위한 include
using namespace std;
 
int main(void){
    while(1){
        int x;
        int y;
        char opr; //operator를 구별하기 위한 대입용 캐릭터형 변수
        Add a; Sub s; Mul m; Div d; //각 클래스 객체 생성
        cout<<"두 정수와 연산자를 입력하세요>>";
        cin>>x>>y>>opr;
        if(opr=='+'){ //opr이 +면
            a.setValue(x,y); //operand 값 set 해주고
            cout<<a.calculate()<<endl//계산값 출력
        }
        else if(opr=='-'){ //opr이 -면
            s.setValue(x,y);
            cout<<s.calculate()<<endl;
        }
        else if(opr=='*'){ //opr이 *면
            m.setValue(x,y);
            cout<<m.calculate()<<endl;
        }
        else if(opr=='/'){ //opr이 /면
            d.setValue(x,y);
            cout<<d.calculate()<<endl;
        }
    }
    return 0;
}
 
cs




반응형
반응형

Oval 클래스는 주어진 사각형에 내접하는 타원을 추상화한 클래스이다. Oval 클래스의 멤버는 모두 다음과같다. Oval 클래스를 선언부와 구현부로 나누어 작성하라. 

1. 정수값의 사각형 너비와 높이를 가지는 width, height 변수 멤버 

2. 너비와 높이 값이 매개 변수로 받는 생성자 

3. 너비와 높이를 1로 촉기화하는 매개 변수 없는 생성자 

4. Width와 height를 출력하는 소멸자 

5. 타원의 너비를 리턴하는 getWidth() 함수멤버 

6. 타원의 높이를 리턴하는 getHeight() 함수멤버

7. 타원의 너비와 높이를 변경하는 set(int w,int h) 함수멤버

8. 타원의 너비와 높이를 화면에 출력하는 show()함수 멤버


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
48
#include <iostream>
 
using namespace std;
 
class Oval {
private:
    int width;
    int height;
public:
    Oval(int a, int b) {
        width = a;
        height = b;
    }
    Oval() {
        width = 1;
        height = 1;
    }
    ~Oval() {
        cout <<"Oval 소멸 "<< "width : " << width << " " << "height : " << height << endl;
    }
    int getWidth() {
        return width;
    }
    int getHeight() {  //클래스 선언부에 직접 구현된 함수는 인라인 함수가 된다.
        return height;
    }
    void set(int w, int h);
    void show();
    
};
 
void Oval::set(int w, int h) { //width와 height를 셋 해주는 함수
    width = w;
    height = h;
}
void Oval::show() {  //width 와 height 출력 함수
    cout << "width : " << width << " " << "height : " << height << endl;
}
 
int main(void) {
    Oval a;  //Oval 형 객체 a 생성자 매개변수 없는 것이 호출되어 1,1 로 width와 height 초기화
    Oval b(34); //Oval 형 객체 b 3,4 로 width와 height 초기화
    a.set(1020); //a의 height와 width 를 10,20으로 셋
    a.show(); //출력
    cout << b.getWidth() << "," << b.getHeight() << endl//get 함수로 b의 width와 height 출력 직접 접근은 불가(private이라서)
 
    return 0;
    }
cs




반응형

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

SelectableRandom 클래스  (0) 2017.10.12
EvenRandom 클래스  (0) 2017.10.12
랜덤 수 출력  (0) 2017.09.16
별 출력  (0) 2017.09.09
1부터 10까지 더하기  (0) 2017.09.09
반응형

7.8>다음은 String만 다루는 MyClass 코드이다. MyClass를 제네릭 클래스 MyClass<E>로 일반화하고, 이를 이용하는 main() 메소드를 만들어 프로그램을 완성하라.


public class MyClass {

      private String s;

      public MyClass(String s) {

            this.s = s;

      }

      void setS(String s) {

            this.s = s;

      }

      String getS() {

            return s;

      }

}


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
package SecondHW;
class MyClass<E> {  //제네릭 클래스 MyClass 타입 매개 변수는 E, 설정하는 것에 따라 자유자재로 바뀜
    private E e; //private 형이라서 Myclass내 접근이 아니면 변경 불가한 E형 변수 e
    public MyClass(E e) { //생성자 ,매개변수를 객체 e 에 대입
        this.e = e;
    }
    void setS(E e) { //e를 정해주는 setS메소드 매개변수 e를 객체의 e에 대입 디폴트형
        this.e = e;
    }
    E getS() {  //객체의 e를 반환해주는 getS메소드 디폴트형
        return e;
    } //제네릭은 클래스와 인터페이스에만 적용되므로 자바 기본 타입은 사용 불가능
}
public class GenericPractice {
    public static void main(String[] args) {
        MyClass<Integer> i = new MyClass<Integer>(1); //정수형 MyClass i 래퍼 클래스 사용 
        MyClass<Double> d = new MyClass<Double>(2.7); //실수형 MyClass d 래퍼 클래스 사용
        MyClass<String> s = new MyClass<String>("For the Horde"); //문자열형 Myclass s
        System.out.println(i.getS()); //getS함수를 통해 리턴된 값 출력
        System.out.println(d.getS());
        System.out.println(s.getS());
        i.setS(3); //i의 e를 3으로 set
        d.setS(3.14); //d의 e를 3.14으로 set
        s.setS("탕수육소스다");//s의 e를 "탕수육소스다"로 set
        System.out.println(i.getS());
        System.out.println(d.getS());
        System.out.println(s.getS()); //출력
    }}
 
cs




반응형

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

학생 정보  (0) 2017.06.19
학점 계산  (0) 2017.06.19
가장 큰 수  (0) 2017.06.19
겜블링 게임  (0) 2017.06.19
가위바위보  (0) 2017.06.19
반응형

6.12> 겜블링 게임을 만들어보자. 두 사람이 게임을 진행한다. 두 사람의 이름은 처음에 키보드를 통해서 입력 받는다. 게임에 참여하는 사람은 Person클래스로 작성하도록 하라. 각 사람이 번갈아 가면서 게임을 진행한다. 각 사람이 자기 차례에서 <Enter> 키를 입력하면 프로그램은 3개의 난수를 발생시키고 이 3개의 숫자가 모두 같은 지 판단한다. 동일하다면 승자가 되며 게임을 끝낸다. 게임은 끝날 때까지 두 사람이 번갈아 가면서 진행한다. 숫자의 범위를 너무 크게 잡으면 3개의 숫자가 일치하게 나올 가능성이 적기 때문에 편리를 위해 숫자의 범위는 0~3까지만 한다.


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
package SecondHW;
import java.util.*//스캐너 사용 위한 임포트
class Person{String name;} //Person 클래스와 그 원소 문자열 name
public class Gembling {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in); //스캐너객체 s
        Person p1=new Person(); //Person 객체 를가리키는 레퍼런스 변수 p1
        Person p2=new Person(); //Person 객체 를가리키는 레퍼런스 변수 p2
        int rand[]= new int[3]; //사이즈3의 인트형 배열 rand
        int round=1//int형변수 round 선언 및 1로 초기화
        int who=0//int형변수 who 선언 및 0으로 초기화
        System.out.print("플레이어1의 이름을 입력하세요: ");
        p1.name=s.nextLine(); //p1.name을 nextLine으로 받음(개행문자 미포함)
        System.out.print("플레이어2의 이름을 입력하세요: ");
        p2.name=s.nextLine();//p2.name을 nextLine으로 받음(개행문자 미포함)
        while(true){
            who=round%2//who는 round를 2로나눈 나머지 즉 홀수면 p1, 짝수면 p2
            if(who==1){
                System.out.print(p1.name + "님 차례입니다. 엔터 입력>>");
            }
            else if(who==0){
                System.out.print(p2.name + "님 차례입니다. 엔터 입력>>");
            }
            String check=s.nextLine(); //문자열 check를 nextLine으로 받음(nextLine은 개행 미포함)
            //즉 엔터만 치면 빈 문자열이 됨.
            if(check.isEmpty()){  // isEmpty : 스트링길이0이면true, 아니면 false
                for(int i=0;i<3;i++//3번 반복
                {    rand[i]=(int)(Math.floor(Math.random()*4)); 
                // 균일한 확률을 위해 곱하기 4한 후 내림 사용
                    System.out.print(rand[i]+" ");} //각 원소 출력
                System.out.println();} //3개 출력후개행문자 출력
            if((rand[0]==rand[1])&&(rand[1]==rand[2])) //0번,1번,2번 원소가 전부 같으면
            {if(who==1){ //p1일때
                System.out.println(p1.name+"님의 승리입니다 축하합니다!" );
                break;} //승리축하문자 출력후 루프 탈출
            else if(who==0){//p2일때
                System.out.println(p2.name+"님의 승리입니다 축하합니다!" );
                break;}} //승리축하문자 출력후 루프 탈출
            round++//승리하지못했을시 round증가시키고 루프 반복
        }}}
 
cs






반응형

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

학점 계산  (0) 2017.06.19
가장 큰 수  (0) 2017.06.19
가위바위보  (0) 2017.06.19
대문자 개수 세기  (0) 2017.06.19
메소드 오버라이딩  (0) 2017.06.18
반응형

6.6> ctrl-z가 입력될 때까지 키보드로부터 영어 문자를 읽고 그 속에 대문자가 몇 개 있는지 판별하는 프로그램을 작성하라


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package SecondHW;
import java.io.*//InputStreamReader 사용을 위한 패키지 import
public class CapitalAlphabet {
    public static void main(String[] args) {
        int count=0;
        InputStreamReader rd = new InputStreamReader(System.in); //키 입력을 문자 정보로 변환하여 리턴하는 클래스
        try{
            while(true){ //무한 반복
                int c=rd.read(); //int 형 변수 c에 키 입력 받는 것 대입
                if(c==-1//c==-1이면, 즉 Ctrl+z가 입력되면
                    break//무한루프 탈출
                if(c>='A'&&c<='Z'//c가 A이상 Z이하면 (실제로는 아스키코드(유니코드의 첫부분은 아스키코드와 같아서)값으로 논리 판단)
                    count++//카운트 증가
                System.out.print((char)c); //c 를 캐릭터 형으로 출력
            }
            System.out.println("대문자는 "+count+"개 입니다."); //count 를 정수형으로 출력
        }
        catch(IOException e){ //입출력 동작 실패시
            System.out.println("입력 오류 발생"); //해당문구 출력
        }
    }
}
 
cs



반응형

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

겜블링 게임  (0) 2017.06.19
가위바위보  (0) 2017.06.19
메소드 오버라이딩  (0) 2017.06.18
추상 클래스  (0) 2017.06.18
상속 클래스  (0) 2017.06.18
반응형

4.4 다음 두 개의 static 메소드를 가진 ArrayUtility2 클래스를 만들어보자. ArrayUtility2 클래스를 이용하는 테스트용 프로그램도 함께 작성하라.


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
package HW1_JAVA;
class ArrayUtility2{//s1과 s2를 연결한 새로운 배열 리턴
    static int[] concat(int s1[], int s2[]){ //int형배열을 리턴으로하는 메소드 concat(인자 int형배열 2개)
        int conc[]=new int[s1.length+s2.length]; //s1과 s2 길이를 더한 길이를 갖는 인트형 배열 conc
        int i; //int 형 변수 i 선언
        for(i=0;i<conc.length;i++//i=0부터 conc의 길이보다 작을 때까지 반복
        {
            if(i<=4//i가  4 이하이면 conc[i]에 s1[i] 대입
            conc[i]=s1[i];
            else    //i가 5이상이면 conc[i]에 s2[i-5] 대입
            conc[i]=s2[i-5];
        }
        return conc;}  //conc 배열 리턴
    static int[] remove(int s1[], int s2[]){ //s1에서 s2 배열의 숫자를 모두 삭제한 새로운 배열 리턴
        int i; int j; //인트형 변수 i,j 선언
        int s3[]=new int[s1.length]; //s1.length의 길이를 갖는 배열 s3 선언
        LABEL : for(i=0;i<s1.length;i++//i는 0부터 s1.length 미만까지 반복
        {
            for(j=0;j<s2.length;j++//j는 0부터 s2.length 미만까지 반복
            {
                if(s1[i]==s2[j])  //s1[i]와 s2[j]가 같으면 루프 중단 후 LABEL로 점프(증가식은 진행됨)
                    continue LABEL;
            }
            s3[i]=s1[i]; //s3[i]에 s1[i] 대입
        }
        return s3;} } //배열 s3 리턴
public class ArrUse {
    public static void main(String[] args) {
        ArrayUtility2 ut=new ArrayUtility2(); //ArrayUtility2 class의 객체와 레퍼런스 변수 선언
        int a[]={1,2,3,4,5}; //int형 배열 a 선언 및 초기화
        int b[]={3,4,5,6,7}; //int형 배열 b 선언 및 초기화
        int c[]=new int[a.length+b.length]; //int형 배열 c 선언
        int d[]=new int[a.length]; //int형 배열 d 선언
        int i; //int형 변수 i 선언
        c=ut.concat(a, b); //배열 c에 concat 메소드의 리턴값 대입
        d=ut.remove(a, b); //배열 d에 remove 메소드의 리턴값 대입
        for(i=0;i<c.length;i++//i=0부터 c.length 미만까지 반복
        {
            System.out.print(c[i]+" "); //c[i]와 띄어쓰기 출력
        }
        System.out.println(); // 개행문자 출력
        for(i=0;i<d.length;i++//i=0부터 d.length 미만까지
        {
            if(d[i]!=0//int형 배열은 0으로 자동초기화 되기 때문에 출력안하려면 논리판별
            System.out.print(d[i]+" "); //d[i]와 띄어쓰기 출력
        }}}
 
cs






반응형

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

추상 클래스  (0) 2017.06.18
상속 클래스  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18
돈 단위 나누기  (0) 2017.06.18
2차원 배열  (0) 2017.06.18
반응형

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

3.11>배열과 반복문을 이용하여 프로그램을 작성해보자. 키보드에서 정수로 된 돈의 액수를 입력 받아 오만 원권, 만 원권, 천 원권, 500원짜리 동전, 100원짜리 동전, 50원짜리 동전, 10원짜리 동전, 1원짜리 동전이 각 몇 개로 변환되는지 출력하라. 예를 들어 65370이 입력되면 오만 원권 1, 만 원권 1, 천 원권 5, 100원짜리 동전 3, 50원짜리 동전 1, 10짜리 동전 2개이다. 이때 반드시 다음의 배열을 이용하고 반복문으로 작성하라.


int []unit={50000,10000,1000,500,100,50,10,1}; //환산할 돈의 종류


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
package HW1_JAVA;
import java.util.Scanner//Scanner 클래스의 위치
class Sort{ //Sort 클래스 선언
    void sorting(int arr[], int gold){ //sorting 메소드 선언 인자 int형 배열 arr, int형 변수 gold
        int i;  int d;  //int형 변수 i, d 선언
        for(i=0;i<arr.length;i++//isms 0부터 배열 arr의 길이보다 작을 때까지
        {d=gold/arr[i]; //d는 gold를 arr[i]로 나눈 것의 몫
            if(d==0//d가 0이면 루프를 완전히 돌지 않고 i를 증가시킨 후 다시 돌게 만든다.
                continue;
            if(i<=2//i가 2 이하이면 원과 매로 출력
                System.out.println(arr[i]+"원권 "+d+"매");
            else  //i가 2초과이면 동전과 개로 출력
                System.out.println(arr[i]+"원짜리 동전 "+d+"개");
        gold%=arr[i];  // gold = gold % arr[i] 와 같다. (나머지)
        }    
    }
}
public class MoneyDivison { //class MoneyDivison 선언
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in); //Scanner 클래스 객체와 레퍼런스 변수 선언
        Sort so = new Sort(); //Sort 클래스 객체와 레퍼런스 변수 선언
        int []unit={50000,10000,1000,500,100,50,10,1}; // int형 배열 unit 선언과 초기화
        System.out.print("금액을 입력하세요>>");
        int gold=s.nextInt(); // int형 변수 gold 선언과 정수형 입력
        so.sorting(unit, gold); //sorting 메소드를 unit배열과 gold변수를 넣어 호출
    }
}
 
cs




반응형

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

ArrayUtility class  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18
2차원 배열  (0) 2017.06.18
정수 오름차순 정렬기  (0) 2017.06.18
하위 문자 모두 출력하기  (0) 2017.06.18

+ Recent posts