본문 바로가기

프로그래밍 언어들/C++

CHAPTER12 - String 클래스의 디자인

1. C++의 표준과 표준 String 클래스

string 클래스를 모델로 삼아서 연산자가 어떠한 형태로 오버로딩 되어 있는지 고민해 보고,

이와 유사한 문자열 처리 클래스를 직접 구현해 보는데 목적이 있다.


1.1 표준 string 클래스의 분석

먼저, string 클래스의 정의를 위해서 어떠한 것들이 요구되는지 하나씩 정리해 보겠다.

(1) 문자열을 인자로 전달받는 생성자의 정의

(2) 생성자, 소멸자, 복사 생성자 그리고 대입 연산자의 정의

(3) 결합된 문자열로 초기화된 객체를 반환하는 + 연산자의 오버로딩

(4) 문자열을 덧붙이는 += 연산자의 오버로딩

(5) 내용비교를 진행하는 == 연산자의 오버로딩

(6) 콘솔입출력이 가능하도록 >>, << 연산자의 오버로딩


1.2 String 클래스의 완성

class String
{
private:
    int len;
    char *str;
public:
    String(const char *c)
    {
        len = strlen(c) + 1;
        str = new char[len];

        strcpy(str, c);
    }
    String(const String& ref)
    {
        len = ref.len;
        str = new char[len];

        strcpy(str, ref.str);
    }
    ~String(void)
    {
        if(str != NULL)
        {
            delete []str;
        }
    }

    String& operator+=(const String&);
    String& operator=(const String&);
    String operator+(const String&);
    bool operator==(const String&);
    friend ostream& operator<<(ostream&, const String&);
    friend istream& operator>>(istream&, const String&);
};
String& String::operator+=(const String& ref)
{
    len         = len + ref.len - 1;
    char *ctemp = new char[len];

    strcpy(ctemp, str);
    strcat(ctemp, ref.str);

    if(str != NULL)
    {
        delete []str;
    }

    str = ctemp;

    return *this;
}
String& String::operator=(const String& ref)
{
    if(str != NULL)
    {
        delete []str;
    }

    len = ref.len;
    str = new char[len];

    strcpy(str, ref.str);

    return *this;
}
String String::operator+(const String& ref)
{  
    char *temp  = new char[len + ref.len - 1];

    strcpy(temp, str);
    strcat(temp, ref.str);

    String stemp(temp);
    delete []temp;

    return stemp;
}
bool String::operator==(const String& ref)
{
    return strcmp(str, ref.str)? false : true;
}
ostream& operator<<(ostream& os, const String& ref)
{
    os << ref.str;
    fflush(stdout);
    return os;
}
istream& operator>>(istream& is, String& ref)
{
    char ch[30];
    is >> ch;

    ref = String(ch);

    return is;
}
int main(void)
{
    String str1 = "I CAN DO ";
    String str2 = "IT!";
    String str3 = str1 + str2;

    cout << str3 << endl;

    String str4 = str3;
    str1    += str2;

    if( str1 == str4)
    {
        cout << "같다" << endl;
    }
    return 0;
}
I CAN DO IT!
같다


충분히 이해하리라 생각된다.


출처 : 윤성우 열혈 C++ 프로그래밍