플밍/C++ (overview)

string 클래스 디자인

천재차씨 2012. 1. 3. 23:18

2006/08/31 02:47


시작에 앞서..

 

많은 reference서적이 있고, 기본과 원칙 보다는 이를 활용하는 디자인이 더 중시되고 있는데,

그렇다고 절대로 기본과 원칙을 무시해서는 안된다.

기본기가 탄탄해야 한다. 스택과 리스트 구조를 가져다 쓸수는 있지만, 자체를 직접 구현할수

없다면 속빈 강정이지 뭐.. -_- 그런 의미로 string 클래스를 직접 구현해보자.

 

=======================================================================================

 

표준 string 클래스

 

C++ 표준 library에는 문자'열'을 다루기 쉽도록, string 클래스가 만들어져 있다.

사용할때는 헤더 파일 string 을 포함해야 한다.

 

직접 구현을 위해 고려할 점

 

첫번째. 문자열은 길이가 일정치 않기때문에 동적할당을 해야 하므로,

           생성자, 소멸자, 복사생성자, 대입연산자를 주의깊게 정의해야 한다.

 

두번째. +, <<, +=, ==, >> 를 오버로딩 해야 한다.

 

=======================================================================================

#include <iostream>

using std::endl;
using std::cout;
using std::cin;

using std::ostream;
using std::istream;

class string{
      int len;
      char* str;
public:
      string(const char* s=NULL);
      string(const string& s);
      ~string();
      string& operator=(const string& s);
      string& operator+=(const string& s);
      bool operator==(const string& s);
      string operator+(const string& s);

      friend ostream& operator<<(ostream& os, const string& s);
      friend istream& operator>>(istream& is, string& s);
};

string::string(const char* s){
      len=(s!=NULL ? strlen(s) + 1 : 1);
      str = new char[len];

      if(s!=NULL)
            strcpy(str, s);
}
string::string(const string& s){
      len=s.len;
      str=new char[len];
      strcpy(str, s.str);
}
string::~string(){
      delete []str;
}
string& string::operator=(const string& s){
      delete[] str;
      len=s.len;
      str=new char[len];
      strcpy(str, s.str);
      return *this;
}
string& string::operator+=(const string& s){
      len=len+s.len-1;
      char* tStr =new char[len];
      strcpy(tStr, str);
      delete[] str;
      strcat(tStr, s.str);
      str=tStr;
      return *this;
}
bool string::operator==(const string& s){
      return strcmp(str, s.str)? false : true;
}
string string::operator+(const string& s){
      char* tStr=new char[len+s.len-1];
      strcpy(tStr, str);
      strcat(tStr, s.str);
      string temp(tStr);
      delete[]tStr;
      return temp;
}
ostream& operator<<(ostream& os, const string& s){
      os<<s.str;
      return os;
}
istream& operator>>(istream& is, string& s){
      char str[100];
      is>>str;
      s=string(str);
      return is;
}

int main(){
      string str1="Good ";
      string str2="morning.";
      string str3=str1+str2;

      cout<<str1<<endl;
      cout<<str2<<endl;
      cout<<str3<<endl;

      str1+=str2;

      if(str1==str3){
            cout<<"equal!" << endl;
      }

      string str4;

      cout<<"input string : " ;
      cin>>str4;
      cout << "String you input : " << str4 << endl;
      return 0;
}