#include <bits/stdc++.h>
using namespace std;
class String {
public:
String() {
buf = new char[1];
buf[0] = '\0';
len = 0;
}
~String() {
if (buf != nullptr) {
delete [] buf;
buf = nullptr;
}
}
//有参构造
String(const char* src) {
if (src == nullptr) {
len = 0;
buf = new char[1];
buf[0] = '\0';
return;
}
len = strlen(src);
buf = new char[len + 1];
strcpy(buf, src);
}
//拷贝
String(const String& s) {
len = s.len;
buf = new char[len + 1];
strcpy(buf, s.buf);
}
//移动
String(String& s) {
len = s.len;
buf = s.buf;
s.buf = nullptr;
s.len = 0;
}
//赋值
String& operator=(const String& s) {
if (this == &s) return *this;
len = s.len;
buf = new char[len + 1];
strcpy(buf, s.buf);
return *this;
}
//左移运算符重载
friend ostream& operator<<(ostream& os, String& s) {
os << s.buf;
return os;
}
//输出大小
size_t size() {
return len;
}
private:
size_t len;
char* buf;
};
int main() {
String s1("hello world");
cout << s1.size() << " " << s1 << endl;
String s2 = s1;
cout << s2.size() << " "<< s2 << endl;
String s3;
cout << s3.size() << " " << s3 << endl;
return 0;
}
C++ 手写String类
最新推荐文章于 2022-11-04 17:02:47 发布