#ifndef STRING_H
#define STRING_H
class String {
public:
//构造函数集合
String();
String( const char *cha );
String( const String& str );
//运算符重载集合
void operator =( const char *cha );
void operator =( const String& str );
const bool operator ==( const char *cha ) const;
const bool operator ==( const String& str ) const;
char& operator[]( const int index ) ;
//内置方法集合
const int lenght(void) const;
const char *c_str(void) const;
private:
//私有函数
void str_init(const int lg,const char *cha);
//私有数据
char *_ch;//字符串头指针
int _lenght;//字符串长度
};
//字符串类的流操作符重载
ostream& operator << (ostream& os,String& obj) {
for(int i = 0;i <= obj.lenght();++i)
os << obj[ i ];
return os;
}
istream& operator >> ( istream& is,String& obj ) {
for( int i = 0;i < obj.lenght();++i )
is >> obj[ i ];
return is;
}
//私有函数集合
void String::str_init( const int lg,const char *cha ) {
if(!cha){
_lenght = 0;
_ch = 0;
}
else {
_lenght = lg;
_ch = new char [ _lenght + 1 ];
strcpy( _ch,cha );
}
}
//公有函数集合
//构造函数集合
String::
String(){ str_init( 0,0 ); }
String::
String(const char *cha) { str_init(strlen(cha),cha); }
String::
String(const String& str){ str_init(str._lenght,str._ch);}
//方法集合
const int String::lenght() const { return _lenght;}
const char* String :: c_str() const { return _ch;}
//操作符集合
char& String::operator[]( const int index )
{
assert(index >= 0 && index <= _lenght);
return _ch[ index ];
}
const bool String::operator ==( const String& str ) const
{
if( str._ch )
return false;
if( _lenght != str._lenght )
return false;
if( strcmp( _ch,str._ch ) )
return false;
return true;
}
const bool String::operator ==( const char *cha ) const
{
if( cha )
return false;
if( _lenght != strlen( cha ) )
return false;
if( strcmp( _ch,cha ) )
return false;
return true;
}
void String::operator =( const String& str )
{
if( !str._ch ){
_lenght = 0;
delete [] _ch;
_ch=0;
}
else {
_lenght = str._lenght;
delete [] _ch;
_ch=new char [ _lenght + 1 ];
strcpy( _ch,str._ch );
}
return ;
}
void String::operator = ( const char *cha )
{
if( !cha ) {
_lenght = 0;
delete [] _ch;
_ch = 0;
}
else {
_lenght = strlen( cha );
delete [] _ch;
_ch=new char [ _lenght + 1 ];
strcpy(_ch,cha);
}
return ;
}
#endif