实现一个string类
作者:
诺亚方舟.
,
2021-09-16 15:58:14
,
所有人可见
,
阅读 302
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
class MyString {
public:
//构造函数
MyString(const char* str = nullptr) {
if (str != nullptr) {
m_data = new char[strlen(str) + 1];
strcpy(m_data, str);
} else {
m_data = new char[1];
*m_data = '\0';
}
}
//析构函数
~MyString() {
delete[] m_data;
m_data = NULL;
}
// 拷贝构造函数
MyString(const MyString& other) {
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
}
// 拷贝赋值函数 =号重载
MyString& operator=(const MyString& other) {
if (this == &other) //避免自我赋值
return *this;
delete[] m_data;
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
return *this;
}
char* get_c_str() const { return m_data; }
private:
char* m_data;
};
ostream& operator<<(ostream& os, const MyString& str)
{
os << str.get_c_str();
return os;
}
int main()
{
MyString s1("hello");
MyString s2("world");
MyString s3(s2);
cout << s3 << endl;
s3 = s1;
cout << s3 << endl;
cout << s2 << endl;
cout << s1 << endl;
return 0;
}