仿写几个String类函数
#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
public:
//无参构造函数
mystring()
{
str = nullptr;
len = 0;
}
//有参构造函数
mystring(const char *s)
{
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
//拷贝构造函数
mystring(const mystring &other)
{
len = other.len;
str = new char[len + 1];
strcpy(str, other.str);
}
//拷贝赋值函数
mystring & operator = (const mystring &other)
{
if(&other != this)
{
len = other.len;
if(str == nullptr)
{
str = new char[len + 1];
}
else
{
delete []str;
str = nullptr;
}
strcpy(str, other.str);
}
return *this;
}
~mystring()
{
if(str != nullptr)
{
delete []str;
str = nullptr;
}
}
char *data()
{
return str;
}
int size()
{
return len;
}
bool empty()
{
if(len != 0)
{
return false;
}
else
{
return true;
}
}
char& at(int index)
{
if(index >=0 && index <= len - 1)
{
return str[index];
}
else
{
cout << "下标超出范围" << endl;
return str[0];
}
}
private:
char *str;
int len;
};
int main(int argc, const char *argv[])
{
mystring s1("hello world");
cout << s1.data() << endl;
cout << s1.size() << endl;
cout << s1.empty() << endl;
cout << s1.at(4) << endl;
return 0;
}
运行结果