用c++写一个string类的封装
时间: 2023-09-01 14:13:29 浏览: 57
下面是一个简单的 C++ string 类的封装,包含了一些常用的字符串操作方法:
```c++
#include <iostream>
#include <cstring>
class String {
public:
// 默认构造函数
String() : m_data(nullptr), m_size(0) {}
// 构造函数
String(const char* str) : m_data(nullptr), m_size(0) {
if (str != nullptr) {
m_size = strlen(str);
m_data = new char[m_size + 1];
std::strcpy(m_data, str);
}
}
// 拷贝构造函数
String(const String& other) : m_data(nullptr), m_size(0) {
if (other.m_data != nullptr) {
m_size = other.m_size;
m_data = new char[m_size + 1];
std::strcpy(m_data, other.m_data);
}
}
// 析构函数
~String() {
if (m_data != nullptr)
delete[] m_data;
}
// 获取字符串长度
size_t size() const {
return m_size;
}
// 获取字符串是否为空
bool empty() const {
return m_size == 0;
}
// 获取 C 风格字符串
const char* c_str() const {
return m_data;
}
// 重载赋值运算符
String& operator=(const String& other) {
if (this == &other)
return *this;
if (m_data != nullptr)
delete[] m_data;
m_size = other.m_size;
m_data = new char[m_size + 1];
std::strcpy(m_data, other.m_data);
return *this;
}
// 重载加号运算符
String operator+(const String& other) const {
String result;
result.m_size = m_size + other.m_size;
result.m_data = new char[result.m_size + 1];
std::strcpy(result.m_data, m_data);
std::strcat(result.m_data, other.m_data);
return result;
}
// 重载加等于运算符
String& operator+=(const String& other) {
*this = *this + other;
return *this;
}
// 重载下标运算符
char& operator[](size_t index) {
return m_data[index];
}
const char& operator[](size_t index) const {
return m_data[index];
}
private:
char* m_data;
size_t m_size;
};
int main() {
String str1("Hello");
String str2(" World");
str1 += str2;
std::cout << str1.c_str() << std::endl;
return 0;
}
```
这个封装的 string 类比较简单,只包含常用的一些操作方法。如果需要更加完善的 string 类,可以参考 C++ 标准库中的 std::string 类的实现。