http://blog.csdn.net/moxiaomomo/article/details/6411584
这里就String类中常见成员函数做简单的分析:
class MyString{
public:
MyString(const char* str=NULL);//使用默认参数的构造函数
MyString(const MyString& another);//拷贝构造函数
MyString& operator=(const MyString& another);//赋值运算符,返回的是引用
~MyString();
MyString operator+(const MyString& another);
MyString& operator+=(const MyString& another);//返回的是引用
char operator[](const unsigned int index);
friend ostream& operator<<(ostream&,MyString&);
friend istream& operator>>(istream&,MyString&);
bool operator==( const MyString&);
MyString& append(const MyString&);
int size();
bool empty();
const char* c_str();
private:
char* m_data;
};
MyString::MyString(const char* str){
if(!str)
m_data=NULL;
else{
m_data=new char[strlen(str)+1];//加上尾部'\0'
strcpy(m_data,str);
}
}
MyString::MyString(const MyString& another){
if(!another.m_data)
m_data=NULL;
else{
m_data=new char[strlen(another.m_data)+1];
strcpy(m_data,another.m_data);
}
}
MyString& MyString::operator=(const MyString& another){
if(this!=&another){//判断是否指向同一块内存
delete[] m_data;
if(!another.m_data)
m_data=NULL;
else{
m_data=new char[strlen(another.m_data)+1];
strcpy(m_data,another.m_data);
}
}
return *this;
}
MyString::~MyString(){
delete [] m_data;
m_data=NULL;
}
MyString MyString::operator+(const MyString& another){
MyString newstr;
newstr.m_data=new char[strlen(m_data)+strlen(another.m_data)+1];
strcpy(newstr.m_data,m_data);
strcat(newstr.m_data,another.m_data);
return newstr;
}
MyString& MyString::operator+=(const MyString& another){
char* temp=new char[strlen(m_data)+strlen(another.m_data)+1];
strcmp(temp,m_data);
strcat(temp,another.m_data);
delete[] m_data;
m_data=new char[strlen(m_data)+strlen(another.m_data)+1];
strcmp(m_data,temp);
delete[] temp;
temp=NULL;
return *this;
}
char MyString::operator[](const unsigned int index){
if(index>=0 && index<=strlen(m_data))// 元素个数是strlen(m_data)+1
return m_data[index];
}
ostream& operator<<(ostream& outstream,MyString& str){
if(!str.m_data)
outstream<<str.m_data;
return outstream;
}
istream& operator>>(istream& instream,MyString& str){
char temp[255];//临时字符数组
if(instream>>temp){
delete[] str.m_data;
str.m_data=new char[strlen(temp)+1];
strcpy(str.m_data,temp);
}
return instream;
}
bool MyString::operator==(const MyString& str){
return strcmp(m_data,str.m_data)?false:true;
}
MyString& MyString::append(const MyString& str){
char* temp=m_data;
m_data=new char[strlen(temp)+strlen(str.m_data)+1];
strcmp(m_data,temp);
strcat(m_data,str.m_data);
delete[] temp;
temp=NULL;
return *this;
}
int MyString::size(){
return strlen(m_data);
}
bool MyString::empty(){
return strlen(m_data)==0;
}
const char* MyString::c_str(){
return m_data;
}