#include <iostream>
#include <cstring>
#include <vector>
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(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;
}
~MyString() {
delete[] m_data;
m_data = NULL;
}
private:
char* m_data;
};
C++自定义实现string类
最新推荐文章于 2024-06-01 18:28:10 发布