#include <iostream>
#include<cstring>
#include<pthread.h>
//仿照string类,实现myString类
using namespace std;
class myString
{
private:
char *str;//记录c风格的字符串
int size;//记录字符串的实际长度
public:
//无参构造
myString():size(10)
{
str=new char[size];//构造出一个长度为10的字符串
strcpy(str,"");
}
//有参构造
myString(const char *s)
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
}
//拷贝构造
myString(const myString &other):size(other.size)
{
size=other.size;
str=new char[size+1];
strcpy(str,other.str);
}
//析构函数
~myString()
{
delete [] str;
}
//判空函数
bool empty()
{
return size==0;
}
//size函数
int length()
{
return size;
}
//c_str函数
const char* c_str()
{
return str;
}
//at函数
char &at(int pos)
{
char &s=str[pos];
return s;
}
//operator=
myString &operator=(const myString &R)
{
//释放原字符串的内存
delete []str;
//分配新的内存空间
size=R.size;
str=new char[size+1];
//将R.str的内容复制到str
strcpy(str,R.str);
return *this;//返回自身引用
}
//operator[]
char operator[](int n)
{
//返回指定位置的字符
return str[n];
}
//operator+
myString operator+(const myString &R)
{
myString temp;
//计算新字符串大小
temp.size = size + R.size -1;
//分配新字符串内存
temp.str = new char[temp.size+1];
//将第一个字符串复制到新字符串里
strcpy(temp.str,str);
//将第二个字符串连接到新字符串的末尾
strcat(temp.str,R.str);
return temp;
}
//operator+=
myString &operator+=(const myString &R)
{
//计算新的字符串长度
size += R.size;
myString temp;
//将str复制到temp
strcpy(temp.str,str);
//释放空间
delete []str;
//分配新的内存空间
str = new char[size+1];
//将temp 和R.str内容连接到当前字符串中
strcpy(str,temp.str);
strcat(str,R.str);
return *this;//返回自身引用
}
//operator!= 判断两个字符串是否不相等
bool operator!=(const myString &R)
{
return strcmp(str,R.str);
}
//operator==判断两个字符串是否相等
bool operator==(const myString &R)
{
return !strcmp(str,R.str);
}
//operator<判断两个字符串是否小于
bool operator <(const myString &R)
{
return strcmp(str,R.str)<0;
}
//operator>判断两个字符串是否大于
bool operator >(const myString &R)
{
return strcmp(str,R.str)>0;
}
//operator<=判断两个字符串是否小于等于
bool operator <=(const myString &R)
{
return strcmp(str,R.str)<=0;
}
//operator>=判断两个字符串是否大于等于
bool operator >=(const myString &R)
{
return strcmp(str,R.str)>=0;
}
//友元
friend ostream &operator<<(ostream &L,const myString &R);
friend istream &operator>>(istream &L,const myString &R);
};
//operator<< cout
ostream &operator<<(ostream &L,const myString &R)
{
L<<R.str;// 将 myString 对象中的字符串插入到输出流中。
return L;
}
//operator>> cin
istream &operator>>(istream &L,const myString &R)
{
L>>R.str; // 从输入流中读取值并存储到 myString 对象中。
return L;
}
int main()
{
myString str1;
cout<<str1.c_str()<<endl;//输出空字符串
myString str2("ni hao");
cout<<str2.c_str()<<endl;
myString str3=str2;
cout<<str3.c_str()<<endl;
if(!str3.empty())
{
str3.at(0)='h';
str3.at(1)='a';
str3.at(2)='p';
str3.at(3)='p';
str3.at(4)='y';
str3.at(5)=' ';
cout<<"str3="<<str3.c_str()<<endl;
}
myString s1=("hello");
myString s2=("world");
cout<<"s1= "<<s1<<endl;
cout<<"s2= "<<s2<<endl;
cout<<"s1+s2= "<<s1+s2<<endl;
cout<<"s1[0]= "<<s1[0]<<endl;
if(s1!=s2)
{
cout<<"s1!=s2"<<endl;
}else if(s1<s2)
{
cout<<"s1<s2"<<endl;
}else if(s1==s2)
{
cout<<"s1=s2"<<endl;
}
return 0;
}