C++ 手写String类
Posted 每天告诉自己要努力
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ 手写String类相关的知识,希望对你有一定的参考价值。
#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类的主要内容,如果未能解决你的问题,请参考以下文章