C++ 对string重载
#include <iostream>
#include<cstring>
using namespace std;
class myString
{
private:
char *str;
int size;
public:
//无参构造
myString():size(10)
{
str=new char[size];
}
//有参构造
myString(const char *s)
{
size=strlen(s);
str=new char[size +1 ];
strcpy(str,s);
}
//拷贝构造
myString (const myString & other):str(new char(*(other.str))),size(other.size)
{
strcpy(str,other.str);
}
//拷贝赋值
//myString & operator =(const myString &other)
//{
// if(this!=&other)
//{
// size =other.size;
//delete [] str;
//str=new char[size+1];
//strcpy(str,other.str);
//}
//return *this;
//}
//析构函数
~myString()
{
delete [] str;
}
//判空
bool empty()
{
if(this->size==0)
return true;
else
return false;
}
//size函数
int size1()
{
return this->size;
}
//c_str函数
const char *c_str()
{
return str;
}
//at函数
char &at(int pos)
{
if(pos<0||pos>=size)
{
cout<<"段错误"<<endl;
}
return str[pos];
}
//成员版函数调用=运算:
myString &operator = (const myString &R)
{
if(this!=&R)
{
this->size=R.size;
delete [] str;
str=new char[size+1];
strcpy(str,R.str);
}
return *this;
}
//访问指定字节
char &operator [](const int pos)
{
if(pos<0||pos>=size)
{
cout<<"段错误"<<endl;
}
return str[pos];
}
//连接两个字符串
const myString operator +(const myString &R)const
{
myString temp;
temp.size=this->size+R.size;
temp.str=new char[temp.size+1];
strcpy(temp.str,this->str);
strcat(temp.str,R.str);
return temp;
}
//将字符串加到末尾
myString operator +=(const myString &R)
{
this->size=this->size+R.size;
strcat(this->str,R.str);
return *this;
}
//判断两个字符串大小
bool operator >(const myString &R)const
{
if(strcmp(this->str,R.str)>0)
{
return true;
}
return false;
}
bool operator >=(const myString &R)const
{
if(strcmp(this->str,R.str)>0||strcmp(this->str,R.str)==0)
{
return true;
}
return false;
}
friend ostream &operator<<(ostream &L,myString &R);
friend istream &operator>>(istream &L,myString &R);
};
ostream &operator<<(ostream &L,myString &R)
{
L<<R.str<<endl;
}
istream &operator>>(istream &L,myString &R)
{
L>>R.str;
}
int main()
{
myString s1;
s1="dwad";
myString s2("DWADWA");
cout<<"s2= "<<s2.c_str()<<endl;
cout<<"s1 = "<<s1.c_str()<<endl;
myString s3;
s3=s1;
cout<<"s3 = "<<s3.c_str()<<endl;
cout<<"s3.at[3] = "<<s3.at(3)<<endl;
cout<<"s3.size1 = "<<s3.size1()<<endl;
s3=s2;
cout<<"s3 = "<<s3[3]<<endl;
myString s4;
s4=s1+s3;
cout<<"s4 = "<<s4;
s4+=s1;
cout<<"s4 = "<<s4;
if(s2>s1)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(s1>=s2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
cin>>s1;
cout<<s1;
return 0;
}