본문 바로가기
알고리즘-자료구조

[개탱][C++][String 클래스][ Operator Overloading 을 이용하여 String 클래스를 구현 ]

by 개탱 2018. 1. 2.
728x90

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
int main()
{
    String x;
    String y = "hello";
 
    x = "Kim";
    y = x + y;
    cout << x << y << endl ;
}
cs

앞서 배운 Operator Overloading 을 이용하여 String 이라는 클래스를 구현하여 위의 코드와 같이 사용을 해보자. 


http://gaetaeng.tistory.com/33

[Operator Overloading][Operator][Overloading][복소수][complexNumber][1]

http://gaetaeng.tistory.com/34

[Operator Overloading][Operator][Overloading][복소수][complexNumber][2]

http://gaetaeng.tistory.com/35

[Shallow Copy][Deep Copy]


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
116
117
118
119
120
121
122
123
124
125
126
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
using namespace std;
 
class String {
private :
    char* pBuf; // 문자열의 크기를 동적으로 할당하여 
                // 그 위치를 가리키게 하기위한 포인터변수.
    int iLen; // 문자열의 길이를 저장하는 변수
public :
    String(); // default constructor // 아규먼트가 없는 생성자
    String(char* s);
    String(String& s);
    ~String() { // 소멸자 ( 해당 객체가 사라질 때 호출 )
        delete (*this).pBuf;
    }
    int getLength();
 
    String& operator=(char* s) {
        if(pBuf) delete pBuf;

        iLen = strlen(s);

        pBuf = _strdup(s);
        return *this// this 앞에 *(포인터) 를 붙여주게 되면 당사자 자체를 참조가능
    }
    String& operator=(String& s) {
        if(pBuf) delete pBuf;
        iLen = s.iLen;
        pBuf = _strdup(s.pBuf);
        return *this;
    }
    
    String operator+(String& s) {
        char buffer[BUFSIZ];
        if(pBuf != NULL)
            strcpy_s(buffer,BUFSIZ, pBuf);
        if(s.pBuf != NULL)
            strcat_s(buffer, BUFSIZ,s.pBuf);
        return String(buffer);
    }
    String operator+(char* pc) {
        char buffer[BUFSIZ];
        if(pBuf != NULL)
            strcpy_s(buffer,BUFSIZ, pBuf);
        if(pc != NULL)
            strcat_s(buffer, BUFSIZ,pc);
        return String(buffer);
    }
    bool operator==(String& s) {
        if(strcmp(pBuf, s.pBuf) == 0) {
            return true;
        }else {
            return false;
        }
    }
    bool operator==(char* c) {
        if(strcmp(pBuf, c) == 0) {
            return true;
        }else {
            return false;
        }
    }
 
 
    friend  ostream& operator<<(ostream& o,String& s); 
    // 전역함수인 operator<< 에서 pBuf를 사용하게 해주기위해 friend 를 걸어준다
};
String::String() {
    pBuf = NULL// 들어오는 문자열이 없으므로 NULL 을 가리키게 함.
    iLen = 0// 역시나 문자열이 없으니 0으로 초기화
    
}
String::String(char* s) {
    pBuf = _strdup(s);  // char* s로 받아온 문자열을 pBuf 에게 넘겨준다.
    // strdup ::s로 받아오는 문자열을 힙영역에 동적할당을 통하여 문자열을 
    // 저장후 주소를 반환해준다

    iLen = strlen(s); // 처음 받아온 문자열의 길이를 저장해둔다.

}
 
String::String(String& s) {
    //pBuf = s.pBuf; //shallow copy 가리키는 포인터 주소를 넘겨주는 방식
    pBuf = _strdup(s.pBuf); // deep copy 가리키는 포인터의 내용 자체를 복사하여 새로 만들어서 가리키게 하는방식
    // http://gaetaeng.tistory.com/35
 
    iLen = s.iLen;
}
 
ostream& operator<<(ostream& o,String& s) {
    if(s.pBuf == NULL) { // 만약 가지고있는 문자열이 없는경우에는
        o << "NULL(0)" ;
    }else {
        o << s.pBuf << "("<<s.getLength() << ")" ; // pBuf를 전역함수에서 사용하기 위해서 class 내부에 함수를
                        // friend 를 걸어줘야한다.
    }
    return o;
}
int String::getLength() {
    return iLen;
}
int main()
{
    String a("Kim");;
    String b;
    String c = "hello"// 이렇게 처음 정의해주면서 값는 넣는 경우에는
                        // Stirng c("hello"); 와 똑같이 운용된다. (Visual Studio 기준)
    String d(a); // 이미 만들어져있는 String 클래스를 새로생성한 클래스에 집어넣기
 
    b = "hi"// Stirng a("hello"); 와 똑같이 운용된다. (Visual Studio 기준)
            // 하지만 (Visual Studio 기준) 으로만 운용되기 때문에 컴파일러에 따라서 에러가 날수도있다.
            // 그러니 operator= 라는 함수도 operator overloading 를 통하여 만들어주자
    String e = a + b;
    String f = a + "Hi";
    
    cout << a.getLength() << endl;
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cout << d << endl;
    cout << e << endl;
    cout << f << endl;
}
 
cs


댓글