在一些笔试题中,常些要写个字符串实现的类,以下是简单的代码实现。
#include <iostream>
#include <string>
using namespace std;
class Mystring
{
public:
friend ostream &operator<<(ostream &out,const Mystring &str);
friend istream &operator>>(istream &ins,Mystring &str);
Mystring();
Mystring(char *str);
Mystring(const Mystring &str);
~Mystring();
int getlength();
char &operator[](int index); //类似string类通过下标的方式来赋值
Mystring operator+(const Mystring &str);
Mystring operator+(const char *str);
Mystring &operator=(const Mystring &str);
private:
char *p_Address;
int m_size;
};
Mystring::Mystring()
{
p_Address=NULL;
m_size=0;
}
Mystring::Mystring(char *str)
{
p_Address=new char[strlen(str)+1];
m_size=strlen(str);
strcpy(p_Address,str);
}
Mystring::Mystring(const Mystring &str)
{
p_Address=new char[str.m_size+1];
m_size=str.m_size;
strcpy(p_Address,str.p_Address);
}
Mystring::~Mystring()
{
if(p_Address!=NULL)
{
delete [] p_Address;
p_Address=NULL;
m_size=0;
}
}
char &Mystring::operator[](int index)
{
return p_Address[index];
}
int Mystring::getlength()
{
return m_size;
}
ostream & operator<<(ostream &out,const Mystring &str)
{
out<<str.p_Address<<endl;
return out;
}
istream &operator>>(istream &ins,Mystring &str)
{
char buff[1024];
if(str.p_Address!=NULL)
{
delete [] str.p_Address;
str.p_Address=NULL;
}
ins>>buff;
str.p_Address=new char[strlen(buff)+1];
strcpy(str.p_Address,buff);
str.m_size=strlen(buff);
return ins;
}
Mystring & Mystring::operator=(const Mystring &str)
{
this->m_size=str.m_size;
if(this->p_Address!=NULL)
{
delete []this->p_Address;
this->p_Address=NULL;
}
this->p_Address=new char[str.m_size+1];
strcpy(this->p_Address,str.p_Address);
return *this;
}
Mystring Mystring::operator+(const Mystring &str)
{
char *pstr=NULL;
int new_size;
new_size=this->m_size+str.m_size+1;
pstr=new char[new_size];
memset(pstr,0x0,new_size);
strcat(pstr,this->p_Address);
strcat(pstr,str.p_Address);
Mystring tmp(pstr);
delete[] pstr;
return tmp;
}
Mystring Mystring::operator+(const char *str)
{
char *pstr=NULL;
int new_size;
new_size=this->m_size+strlen(str)+1;
pstr=new char[new_size];
memset(pstr,0x0,new_size);
strcat(pstr,this->p_Address);
strcat(pstr,str);
Mystring tmp(pstr); //这个地方的实现很好,省去了多余的代码量
delete[] pstr;
return tmp;
}
int main()
{
Mystring str1("open");
Mystring str2;
cout<<str1;
cin>>str2;
cout<<str2;
cout<<"str1+str2:"<<str1+str2+" hello world"<<endl;
str2[0]='Q';
cout<<str2[4]<<endl;
str1=str2;
cout<<str1<<endl;
cout<<"the new str1+str2:"<<str1+str2<<endl;
return 0;
}