仿照string类完成myString类
class myString
{
private:
char* str;
int size;
public:
myString() :size(10)
{
str = new char[size];
cout << "无参构造" << endl;
}
myString(const char* s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
cout << "有参构造" << endl;
}
myString(const myString& other)
{
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
cout << "拷贝构造" << endl;
}
myString& operator=(const myString& other)
{
if (this != &other)
{
this->size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
}
cout << "拷贝赋值" << endl;
return *this;
}
~myString()
{
delete[]str;
cout << "析构函数" << endl;
}
bool empty()
{
if (size == 0)
{
return 1;
}
else
{
return 0;
}
}
int mysize()
{
return size;
}
char* c_str()
{
return str;
}
char& at(int i)
{
if (i<0 || i>size)
{
cout << "越界" << endl;
}
return *(str + i);
}
void show()
{
cout << "=== " << str << endl;
}
};
int main()
{
myString s1;
myString s2("hello world");
myString s3(s2);
cout << "*********************" << endl;
myString s4;
s4 = s2;
s4.show();
cout << "*********************" << endl;
return 0;
}