#include <iostream>
#include <cstring>
using namespace std;
//定义类
class myString
{
private:
char *str;
int size;
public:
//无参构造
myString():size(10)
{
str=new char[size];
cout<<"无参构造"<<endl;
}
//有参构造
myString(const char *s)
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
cout<<"有参构造"<<endl;
}
//拷贝构造
myString(const myString & other)
{
size=other.size;
str=new char[size+1];
strcpy(str,other.str);
cout<<"拷贝构造"<<endl;
}
//拷贝赋值
myString & operator=(const myString & other)
{
if(this== &other)
{
return *this;
}
delete []str;
size=other.size;
str=new char[size+1];
strcpy(str,other.str);
return *this;
cout<<"拷贝赋值"<<endl;
}
//析构函数
~myString()
{
delete []str;
cout<<"析构函数"<<endl;
}
//判空函数
bool empty()
{
if(strlen(str)==0)
{
return true;
}
else
{
return false;
}
}
//size函数
int length()
{
return size;
}
//c_str函数
const char * c_str()
{
return str;
}
//at函数
char &at(int pos)
{
if(pos>=size||pos<0)
{
cout<<"段错误"<<endl;
}
return str[pos];
}
//=重载 赋值
bool operator=(const myString &other)const
{
strcpy(this->str,other.str);
return str;
}
//[]重载 访问指定位置的字符
char &operator[](const int &pos)const
{
return this->str[pos];
}
//+重载 链接
const myString operator+(const myString &other)
{
strcat(this->str,other.str);
this->size=this->size+other.size;
return *this;
}
//==重载 比较字符串大小
bool operator==(const myString &other)const
{
if(strcmp(this->str,other.str)==0)
{
return true;
}
else
{
return false;
}
}
//<重载 比较字符串大小
bool operator<(const myString &other)const
{
if(strcmp(this->str,other.str)<0)
{
return true;
}
else
{
return false;
}
}
//>重载 比较字符串大小
bool operator>(const myString &other)const
{
if(strcmp(this->str,other.str)>0)
{
return true;
}
else
{
return false;
}
}
friend ostream & operator<<(ostream &L,const myString &O);
friend istream & operator>>(istream &L,const myString &O);
};
//<< 输出
ostream & operator<<(ostream &L,const myString &O)
{
L<<O.str<<" "<<O.size<<endl;
return L;
}
//>> 输入
istream & operator>>(istream &L,const myString &O)
{
L>>O.str;
return L;
}
int main()
{
//有参构造函数
myString s1("word");
cout<<"s1="<<s1.c_str()<<endl;
//拷贝构造函数
myString s2(s1);
cout<<"s2="<<s2.c_str()<<endl;
cout<<"s2.length()="<<s2.length()<<endl;
cout<<"s2.c_str()="<<s2.c_str()<<endl;
cout<<"s2.at(3)="<<s2.at(3)<<endl;
//拷贝复制
myString s3;
if(!s3.empty())
{
s3=s1;
}
cout<<"s3="<<s3.c_str()<<endl;
//=
myString s4="hello";
cout<<"s4="<<s4.c_str()<<endl;
//+
myString s5=s1+s4;
cout<<"s5="<<s5.c_str()<<endl;
//[]
s5[3]='A';
cout<<"s5="<<s5.c_str()<<endl;
//<< >>
myString s6;
cout<<"请输入s6";
cin>>s6;
cout<<s6<<endl;
return 0;
}