仿照string模仿myString类
#include <iostream>
#include <cstring>
#include <string>
#include <exception>
using namespace std;
class myString
{
private:
char *str;
int size;
public:
//无参构造
myString()
{
size=0;
str=new char[size+1];
*str='\0';
}
//有参构造
myString(const char *s)
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
}
//析构函数
~myString()
{
delete [] str;
}
//拷贝构造函数
myString(const myString &other)
{
size=other.size;
str=new char[size+1];
copy(other.str,other.str+size+1,str);
}
//拷贝赋值函数
myString &operator=(const myString &other)
{
if(this!=&other)
{
size=other.size;
str=new char[size+1];
copy(other.str,other.str+size+1,str);
}
return *this;
}
//判空函数
bool empty()
{
if(size==0)
{
return true;
}
else
{
return false;
}
}
//size函数
int Size()
{
return size;
}
//at函数
char &at(int i)
{
if(i<0||i>size-1)
{
cout<<"越界访问"<<endl;
return *(str-1);
}
return *(str+i);
}
//c_str函数
char *c_str()
{
return str;
}
};
int main()
{
cout<<"有参构造:"<<endl;
myString s1("best");
cout<<"s1="<<s1<<endl;
cout<<"拷贝构造:"<<endl;
myString s2(s1);
cout<<"s2="<<s2<<endl;
cout<<"判空、拷贝赋值、size、c_str、at:"<<endl;
myString s3;
if(s3.empty())
{
s3 = s2;
}
cout<<"s3="<<s3.c_str()<<endl;
cout<<"s3.size()="<<s3.Size()<<endl;
cout<<"s3.at(1)="<<s3.at(1)<<endl;
return 0;
}