# string 클래스
C++ 표준 라이브러리에는 string이라는 이름의 클래스가 정의되어 있다. 문자열의 처리를 목적으로 정의된 클래스
이며, 이 클래스의 사용을 위해서는 헤더파일 <string>을 포함해야 한다.
■ string 클래스 따라하기
string 클래스는 지금 구현하는것보다 더 많은 것들을 포함하고 있지만 지금까지 배운것들을 토대로 기본적인
연산자 오버로딩을 통해 string 클래스를 구현해보았다.
① 문자열을 인자로 전달받는 생성자의 정의
② 생성자, 소멸자, 복사생성자 그리고 대입연산자의 정의
③ 결합된 문자열로 초기화된 객체를 반환하는 + 연산자 오버로딩
④ 문자열을 덧붙이는 += 연산자 오버로딩
⑤ 문자열을 비교하는 == 연산자 오버로딩
⑥ 콘솔입출력이 가능하도록 <<.>> 연산자의 오버로딩
C++ 표준 라이브러리에는 string이라는 이름의 클래스가 정의되어 있다. 문자열의 처리를 목적으로 정의된 클래스
이며, 이 클래스의 사용을 위해서는 헤더파일 <string>을 포함해야 한다.
■ string 클래스 따라하기
string 클래스는 지금 구현하는것보다 더 많은 것들을 포함하고 있지만 지금까지 배운것들을 토대로 기본적인
연산자 오버로딩을 통해 string 클래스를 구현해보았다.
① 문자열을 인자로 전달받는 생성자의 정의
② 생성자, 소멸자, 복사생성자 그리고 대입연산자의 정의
③ 결합된 문자열로 초기화된 객체를 반환하는 + 연산자 오버로딩
④ 문자열을 덧붙이는 += 연산자 오버로딩
⑤ 문자열을 비교하는 == 연산자 오버로딩
⑥ 콘솔입출력이 가능하도록 <<.>> 연산자의 오버로딩
#include <iostream>
#include <cstring>
usingnamespacestd;
class String
{
private:
char *str;
int len;
public:
String();
String(constchar* pStr);
String(const String& ref);
~String();
String& operator=(const String& ref);
String operator+(const String& ref);
String& operator+=(String& ref);
booloperator==(const String& ref);
friend ostream& operator<<(ostream& os,const String& ref);
friend istream& operator>>(istream& is,String& ref);
};
String::String()
{
len=0;
str=NULL;
}
String::String(constchar* pStr)
{
len=strlen(pStr)+1;
str=newchar[len];
strcpy(str,pStr);
}
String::String(const String& ref)
{
len=ref.len;
str=newchar[len];
strcpy(str,ref.str);
}
String::~String()
{
if(str!=NULL)
delete []str;
}
String& String::operator=(const String& ref)
{
if(str!=NULL)
delete []str;
len=ref.len;
str=newchar[len];
strcpy(str,ref.str);
return *this;
}
String String::operator+(const String& ref)
{
char *tStr=newchar[len+ref.len-1];
strcpy(tStr,str);
strcat(tStr,ref.str);
String temp(tStr);
delete []tStr;
return temp;
/* '+','='가 오버로딩 된 상태에서 */
// *this = *this + ref;
// return *this;
// 위 코드도 가능하지 않을까?
}
String& String::operator+=(String& ref)
{
char *tStr=newchar[len+ref.len-1];
strcpy(tStr,str);
strcat(tStr,ref.str);
if(str!=NULL)
delete []str;
str=tStr;
return *this;
}
bool String::operator==(const String& ref)
{
return (strcmp(str,ref.str)) ? false : true;
}
/* 전역 함수 오버로딩 */
ostream& operator<<(ostream& os,const String& ref)
{
os<<ref.str;
return os;
}
istream& operator>>(istream& is,String& ref)
{
char temp[256];
is>>temp;
ref=String(temp);
return is;
}
'프로그래밍 > C/C++' 카테고리의 다른 글
Name Mangling(네임 맹글링) (0) | 2011.09.02 |
---|---|
C++ :: 템플릿(Template)의 이해(1) (0) | 2010.08.28 |
C++ :: 스마트 포인터(Smart Pointer), 펑터(Functor) (0) | 2010.08.24 |
C++ :: 연산자 오버로딩(2) 디폴트대입연산자,배열인덱스연산자 (0) | 2010.08.24 |
C++ :: 연산자 오버로딩(1) 산술, 단항 연산자 (0) | 2010.08.22 |
댓글 로드 중…