반응형

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

+ Recent posts