仿照string类,完成myString 类
#include <iostream>
#include <cstring>
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) //string s("hello world")
{
size = strlen(s);
str = new char[size+1];
strcpy(str, s);
}
//拷贝构造
myString(const myString &other):size(other.size)
{
str=new char(other.size+1);
strcpy(str, other.str);
}
//析构函数
~myString()
{
delete str;
cout<<"析构函数"<<endl;
}
//拷贝赋值函数
myString & operator=(const myString &other)
{
if(this!=&other)
{
this->size=other.size;
if(this->str!=NULL)
{
delete this->str;
}
this->str=new char(*other.str);
}
cout<<"拷贝赋值"<<endl;
return *this;
}
//判空函数
bool myemp()const
{
return strlen(str)==0;
}
//size函数
int mysize()const
{
return strlen(this->str)+1;
}
//c_str函数
char *C_str()
{
return this->str;
}
//at函数
char &at(int pos)
{
if(pos>this->size || pos<0)
{
cout<<"pos输入错误 "<<endl;
return this->str[0];
}
return this->str[pos-1];
}
//加号运算符重载
const myString operator+ ( const myString &R)const
{
myString s;
s.str=strcat(this->str,R.str);
s.size=this->size+R.size;
s.show();
return s;
}
//加等于运算符重载
myString operator+= (const myString &R)
{
strcat(this->str,R.str);
this->size +=R.size;
return *this;
}
//关系运算符重载(>)
bool operator> ( const myString &R)const
{
return strcmp(this->str,R.str);
}
//中括号运算符重载
char & operator[](int index)
{
return this->str[index-1];
}
void show()
{
cout<<str<<endl;
}
};
int main()
{
myString s1("hello world");
s1.show();
cout<<s1.at(20)<<endl;
cout<<s1[1]<<endl;
myString s2(s1);
s2.show();
s2+=s1;
myString s3=s2;
s3.show();
if(s3>s1)
{
cout<<"************************"<<endl;
}
myString s4;
cout<<s4.myemp()<<endl;
return 0;
}