반응형

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

5.8> 책의 이름과 가격을 저장하는 다음 Book 클래스에 대해 물음에 답하여라.

(1) Book 클래스의 생성자, 소멸자, set() 함수를 구현하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Book::Book(char* title, int price){ // 타이틀과 가격 초기화
    (this->title)=new char[strlen(title)+1]; //사이즈만큼 동적메모리 할당
    strcpy(this->title,title); //strcpy로 복사
    this->price=price; //price 대입
}
Book::~Book(){
    if(title) //title이 NULL이아니면
        delete []title; //동적메모리 반환
}
void Book::set(char* title, int price){
    if(strlen(this->title)<=strlen(title)) //새로대입하는 문자열의 길이가 기존보다 길면
        {
        delete []title;  //동적메모리반환후
        (this->title)=new char[strlen(title)+1];} //새로 그 길이만큼 동적메모리 받아온다.
    
    strcpy(this->title,title); //strcpy로 복사
    this->price=price;
}
 
cs


(2) 컴파일러가 삽입하는 디폴트 복사 생성자 코드는 무엇인가?


1
2
3
4
5
Book::Book(Book& book){
        this->title=book.title;
        this->price=book.price;
    }
 
cs


(3) 디폴트 복사 생성자만 있을 때 아래 main() 함수는 실행 오류가 발생한다. 다음과 같이 실행 오류가 발생하지 않도록 깊은 복사 생성자를 작성하라.


1
2
3
4
5
6
Book::Book(Book& book){
    (this->title)=new char[strlen(book.title)+1];
    strcpy(this->title,book.title);
    this->price=book.price;
}
 
cs



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
#include <iostream>
#include <cstring>
 
using namespace std;
 
class Book{
private:
    char *title; //제목 문자열
    int price; //가격
public:
    Book(char* title, int price);
    Book(Book& book);
    ~Book();
    void set(char* title, int price);
    void show(){cout<<title<<' '<<price<<"원"<<endl;}
    
};
Book::Book(char* title, int price){ // 타이틀과 가격 초기화
    (this->title)=new char[strlen(title)+1]; //사이즈만큼 동적메모리 할당
    strcpy(this->title,title); //strcpy로 복사
    this->price=price; //price 대입
}
Book::Book(Book& book){
    (this->title)=new char[strlen(book.title)+1];
    strcpy(this->title,book.title);
    this->price=book.price;
}
Book::~Book(){
    if(title) //title이 NULL이아니면
        delete []title; //동적메모리 반환
}
void Book::set(char* title, int price){
    if(strlen(this->title)<=strlen(title)) //새로대입하는 문자열의 길이가 기존보다 길면
        {
        delete []title;  //동적메모리반환후
        (this->title)=new char[strlen(title)+1];} //새로 그 길이만큼 동적메모리 받아온다.
    
    strcpy(this->title,title); //strcpy로 복사
    this->price=price;
}
 
 
int main(void){
    Book cpp("명품C++"10000); //초기화
    Book java=cpp; //깊은복사
    cpp.show(); 
    java.show();
    return 0;
}
 
cs




반응형

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

operator overloading  (0) 2017.11.14
모스 부호  (0) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
반응형

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

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