代码
#include <iostream>
#include<cstring>
using namespace std;
class myString
{
private:
char *str;
int size;
public:
//无参构造
myString():size(10)
{
str=new char[size];//创建一个长度为10的字符串
}
//有参构造
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];
}
};
int main()
{
myString s1;
s1="dwad";
myString s2=s1;
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;
return 0;
}