#include <cstring>
#include <iostream>
class String {
public:
explicit String(const char* cstr = nullptr){//初始化
if (cstr) {
pstr = new char[strlen(cstr) + 1];
len = strlen(cstr);
strcpy(pstr, cstr);
} else {
pstr = new char[1];
len = 0;
*pstr = '\0';
}
}
String(const String& str){//拷贝构造
pstr = new char[str.len + 1];
len = str.len;
strcpy(pstr, str.pstr);
}
String(String&& str) noexcept { //移动构造(右值
if (str.pstr != nullptr) {
pstr = str.pstr;
str.pstr = nullptr;
len = str.len;
}
}
String& operator=(const String& str){ //拷贝复制
if (this == &str) {
return *this;
}
delete[] pstr;
pstr = new char[str.len + 1];
len = str.len;
strcpy(pstr, str.pstr);
return *this;
}
String& operator=(String&& str) noexcept {//移动赋值(右值
if (this != &str) {
delete[] pstr;
pstr = str.pstr;
str.pstr = nullptr;
len = str.len;
}
return *this;
}
~String(){
delete []pstr;
len = 0;
}
int size() const{
return len;
}
char* get_c_str() const {
return pstr;
}
private:
char* pstr;
int len;
};
简单版,其他如 输入输出运算符,[] 等等查看