头文件
// My_string.h
#ifndef MY_STRING_H
#define MY_STRING_H#include <cstring>
#include <algorithm>class My_string {
private:char* data;size_t length;void resize(size_t new_length) {size_t new_capacity = std::max(new_length + 1, length);char* new_data = new char[new_capacity];std::copy(data, data + length, new_data);delete[] data;data = new_data;}public:// 默认构造函数My_string() : data(new char[1]), length(0) {data[0] = '\0';}// 构造函数My_string(const char* str);// 拷贝构造函数My_string(const My_string& other);// 移动构造函数My_string(My_string&& other) noexcept;// 赋值操作符My_string& operator=(const My_string& other);// 移动赋值操作符My_string& operator=(My_string&& other) noexcept;// 析构函数~My_string();// 字符串连接My_string& operator+=(const My_string& other);// 获取字符串长度size_t size() const;// 获取C风格字符串const char* c_str() const;// 打印字符串void print() const;
};#endif // MY_STRING_H
函数体
cpp
// My_string.cpp
#include "My_string.h"
#include <iostream>// 构造函数
My_string::My_string(const char* str) {if (str) {length = std::strlen(str);data = new char[length + 1];std::strcpy(data, str);} else {data = new char[1];length = 0;data[0] = '\0';}
}// 拷贝构造函数
My_string::My_string(const My_string& other) : length(other.length), data(new char[other.length + 1]) {std::strcpy(data, other.data);
}// 移动构造函数
My_string::My_string(My_string&& other) noexcept : data(other.data), length(other.length) {other.data = nullptr;other.length = 0;
}// 赋值操作符
My_string& My_string::operator=(const My_string& other) {if (this != &other) {delete[] data;length = other.length;data = new char[length + 1];std::strcpy(data, other.data);}return *this;
}// 移动赋值操作符
My_string& My_string::operator=(My_string&& other) noexcept {if (this != &other) {delete[] data;data = other.data;length = other.length;other.data = nullptr;other.length = 0;}return *this;
}// 析构函数
My_string::~My_string() {delete[] data;
}// 字符串连接
My_string& My_string::operator+=(const My_string& other) {size_t new_length = length + other.length;resize(new_length);std::strcpy(data + length, other.data);length = new_length;return *this;
}// 获取字符串长度
size_t My_string::size() const {return length;
}// 获取C风格字符串
const char* My_string::c_str() const {return data;
}// 打印字符串
void My_string::print() const {std::cout << data << std::endl;
}
主函数
cpp
// main.cpp
#include "My_string.h"int main() {My_string s1("Hello");My_string s2 = s1; // 调用拷贝构造函数My_string s3;s3 = s1; // 调用赋值操作符My_string s4(std::move(s1)); // 调用移动构造函数s2 += s3;s2.print(); // 输出: HelloHelloreturn 0;
}