仿照string类,实现MyString类
#include <iostream>
#include <cstring>
using namespace std;
class MyString {
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//定义无参构造
MyString() : size(10) {
str = new char[size]; //构造出一个长度为10的字符串
strcpy(str, "");
cout << "MyString::无参构造,this = " << this << endl;
}
//定义有参构造
MyString(const char *s) //string s("hello world")
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
cout << "MyString::有参构造,this = " << this << endl;
}
//定义拷贝构造函数
MyString(const MyString &other) : str(new char[other.size + 1]), size(other.size) {
strcpy(this->str, other.str);
cout << "MyString::拷贝构造,this = " << this << endl;
}
//定义拷贝赋值函数
MyString &operator=(const MyString &other) {
if (this != &other) //防止自己给自己赋值
{
char *p = other.str;
char *q = this->str;
while (*p != '\0') {
*q = *p;
q++;
p++;
}
this->size = other.size;
}
cout << "MyString::拷贝赋值,this = " << this << endl;
return *this;
}
//定义析构函数
~MyString() {
//手动释放堆区空间
delete[]str;
cout << "MyString::析构函数,this = " << this << endl;
}
//判空函数
bool empty() {
if (this->size == 0)
return true;
else
return false;
}
//size函数
const int my_size() const {
return this->size;
}
//c_str函数
const char *c_str() {
return this->str;
}
//at函数
char &at(int pos) {
//法一:
// char *p = this->str;
// while (pos--) {
// p++;
// }
// return *p;
//法二:
// return str[pos];
//发三:
return *(str + pos);
}
};
int main() {
//调用无参构造
MyString s1;
cout << "my_size = " << s1.my_size() << " str1 = " << s1.c_str() << endl;
//调用有参构造
MyString s2("XHJ");
cout << "my_size = " << s2.my_size() << " str2 = " << s2.c_str() << endl;
//调用拷贝构造
MyString s3(s2);
cout << "my_size = " << s3.my_size() << " str3 = " << s3.c_str() << endl;
//调用at函数
cout << "第一个字符:" << s3.at(0) << endl;
cout << "第二个字符:" << s3.at(1) << endl;
cout << "第三个字符:" << s3.at(2) << endl;
//调用有参构造
MyString s4("");
cout << "my_size = " << s4.my_size() << " str4 = " << s4.c_str() << endl;
//调用empty函数
//判断字符串s3是否为空
if (s3.empty())
cout << "s3字符串为空!" << endl;
else
cout << "s3字符串不为空!" << endl;
//判断字符串s4是否为空
if (s4.empty())
cout << "s4字符串为空!" << endl;
else
cout << "s4字符串不为空!" << endl;
s4 = s2;
cout << "my_size = " << s4.my_size() << " str4 = " << s4.c_str() << endl;
}
运行结果如下图: