仿照string完成mystring类
#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)
{
this->size=strlen(s);
str = new char[size+1];
strcpy(this->str,s);
cout << "有参构造"<<endl;
}
//拷贝构造
myString(const myString & other):str(new char(*(other.str))),size(other.size)
{
cout <<"拷贝构造" <<endl;
}
//拷贝赋值
myString & operator = (const myString &other)
{
if(this != &other)
{
this->size = other.size;
strcpy(this->str,other.str);
cout <<"拷贝赋值函数"<<endl;
}
return *this;
}
//析构函数
~myString()
{
delete str;
}
//判空函数
bool isEmpty()
{
return size==0?true:false;
}
//size函数
int CharSize()
{
int lenth = strlen(this->str);
return lenth;
}
//c_str函数
char *c_str()
{
cout << this->str <<endl;
return this->str;
}
//at函数
char &at(int pos)
{
return *(str+pos);
}
};
int main()
{
myString stu;
cout<<"*******"<<endl;
char str[20]="hello world";
myString stu1(str);
cout<<"*******"<<endl;
myString stu2(stu1);
cout<<"*******"<<endl;
myString stu3=stu2;
stu3 = stu1;
cout<<"*******"<<endl;
myString stu4 = stu1;
bool flag=stu4.isEmpty();
cout << flag <<endl;
cout<<"*******"<<endl;
myString stu5 = stu1;
int length = stu5.CharSize();
cout << length <<endl;
cout<<"*******"<<endl;
myString stu6 = stu1;
cout<<stu6.c_str()<<endl;
cout<<"*******"<<endl;
myString stu7 = stu1;
cout<<stu7.at(1)<<endl;
cout<<"*******"<<endl;
return 0;
}