본문 바로가기

Archived(CSE Programming)/cpp

Chap 12. String 클래스의 디자인


Chap 12. String 클래스의 디자인

본 챕터에서는 cpp 표준으로 제공하는 <string> 라이브러리의 string class를 String class로 커버하는 것으로 대체한다.


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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
#include <cstring>
using namespace std;
 
class String
{
    // 멤버변수
private:
    char * str;
    int len;
    // 멤버함수
public:
    String();
    String(const char * s); // 생성자
    String(const String & s); // 복사생성자
    ~String(); // 소멸자
    String & operator=(const String & s);     // 대입연산자 오버로딩
    String operator+(const String & s);     // +연산자 오버로딩
    String & operator+=(const String & s);     // += 연산자 오버로딩
    bool operator==(const String & s);         // ==연산자 오버로딩
    
    friend ostream & operator<<(ostream & coutconst String & s);
    friend istream & operator >> (istream & cin, String & s);
};
 
// ******************메인 함수******************
void main() {
    String str1 = "I like";
    String str2 = "String class";
    String str3 = str1 + str2;
    
    cout << str3 << endl;
 
    str1 += str2;
    cout << str1 << endl;
 
    if (str1 == str3)
        cout << "str1과 str3는 같습니다" << endl;
}
 
String::String() {
    len = 0;
    str = NULL;
}
 
String::String(const char * s) {
    len = strlen(s)+1;
    str = new char[len];
    strcpy(str, s); // 복사
}
 
String::String(const String & s) {
    len = s.len;
    str = new char[len];
    strcpy(str, s.str); // 복사
}
 
String::~String() { // 소멸자
    if (str != NULL)
        delete[]str; // 해제
}
 
String &  String::operator=(const String & s) {     // 대입연산자 오버로딩
    // 기존 string 해제 후 새 string 할당
    delete[]str; // 해제
    len = s.len;
    str = new char[len];
    strcpy(str, s.str); // 복사
 
    // 객체 참조형 반환
    return *this;
}
String & String::operator+=(const String & s) {     // +=연산자 오버로딩
    char tempstr[100];
    strcpy(tempstr, str);
 
    delete[]str;
    len += s.len; // 길이확장
    str = new char[len];
    
    strcat(tempstr, s.str); // 합친 배열 대입
    strcpy(str, tempstr);
    return *this;
}
 
String String::operator+(const String & s) {     // + 연산자 오버로딩
    char * tempstr;
    tempstr = new char[len+s.len-1];
 
    strcpy(tempstr, str); 
    strcat(tempstr, s.str);
 
    // 객체 만들어 반환
    String temp(tempstr);
    delete[] tempstr;
 
    return temp;
}
bool String::operator==(const String & s) {
    return (strcmp(str, s.str)==0)? true : false;
}
 
ostream & operator<<(ostream & coutconst String & s) {
    cout << s.str;
    return cout;
}
 
istream & operator >> (istream & cin, String & s) {
    char str[100];
    cin >> str;
 
    s = String(str);
 
    return cin;
}
cs