这里实现的Cstring就是C++库中的近容器string
class Cstring
{
public:
Cstring(char *p=NULL)//构造函数 带一个参数或不带参数的构造
{
if (p != NULL)
{
mpstr=new char[strlen(p)+1];
strcpy(mpstr,p);
}
else
{
mpstr=new char[1];
*mpstr=0;
}
}
Cstring(const Cstring &src)//因为会发生浅拷贝 所以需要自己定义拷贝构造函数
{
mpstr =new char[strlen(src.mpstr)+1];
strcpy(mpstr,src.mpstr);
}
Cstring & operator=(const Cstring &src)//赋值运算符重载
{
if (this == &src) //防止自赋值
{
return *this;
}
delete []mpstr; //释放原来空间
mpstr=NULL;
mpstr = new char[strlen(src.mpstr) + 1];
strcpy(mpstr,src.mpstr);
return *this;
}
~Cstring()//析构
{
delete []mpstr;
mpstr=NULL;
}
bool operator >(const Cstring &src)//大于运算符的重载
{
return strcmp(mpstr,src.mpstr) > 0 ? true:false;
}
bool operator <(const Cstring &src)//小于运算符的重载
{
return strcmp(mpstr,src.mpstr) < 0 ? true:false;
}
bool operator == (const Cstring &src)//等于运算符的重载
{
return strcmp(mpstr,src.mpstr) == 0 ? true:false;
}
//求字符串长度大小
unsigned int size()const{return strlen(mpstr);}
//[]运算符的重载函数 [] * ->
char & operator[](int i){ return mpstr[i];}
//这里char & 之前加const 主要是因为防止参数被修改 只读的“hello”字符串常量不能被修改
const char & operator[](int i)const {return mpstr[i];}
//返回当前指针
const char * c_str()const{return mpstr;}
private:
char* mpstr;
friend Cstring operator+(const Cstring &left,const Cstring &right);
friend ostream &operator<<(ostream &out,const Cstring &src);
friend istream &operator>>(istream &in,Cstring &src);//输入的src不具备const常性
};
//CString str4 = str3 + "world";
//字符串的连接 这里要注意防止内存泄漏 释放ptmp
Cstring operator+(const Cstring &left,const Cstring &right)
{
int size=strlen(left.mpstr)+strlen(right.mpstr)+2;
char * ptmp= new char[size];
strcpy(ptmp,left.mpstr);
strcat(ptmp,right.mpstr);
Cstring tmp(ptmp);
delete[]ptmp;//手动释放
return tmp;//会调用析构
}
ostream &operator<<(ostream &out,const Cstring &src)
{
out<<src.mpstr;
return out;
}
istream &operator>>(istream &in,Cstring &src)
{
in>>src.mpstr;
return in;
}
int main()
{
Cstring str1("hello");
Cstring str2 = str1 + "world";
Cstring str3 = "china"+ str2;
Cstring str4 = str1 + str3;
cout << "str1:"<<str1 << endl;
cout <<"str2:"<<str2 << endl;
cout << "str3:" << str3 << endl;
cout << "str4:" << str4 << endl;
if (str1 > str2)
{
cout<<"str1 > str2"<<endl;
}
else if (str1 < str2)
{
cout<<"str1 < str2"<<endl;
}
else
{
cout<<"str1 == str2"<<endl;
}
int size = str1.size();
for (int i = 0; i < size; ++i)
{
// str1.operator[](i) char& operator[](int i)
cout << str1[i];
}
cout << endl;
Cstring -> char*
char buffer[1024] = { 0 };
strcpy(buffer, str1.c_str());
cout << buffer << endl;
return 0;
}
执行之后的结果: