C++简单String类的实现 发表于 Apr 8 2015 这里给出了C++面试中String类的一种正确写法,我又添加了一些内容,给出完整的代码。其中赋值操作符的实现用到了一些小技巧,具体可以参见《Effective C++》: 条款10:令operator=返回一个reference to *this(支持形如“x = y = z”的连锁赋值) 条款11:在operator=中处理“自我赋值”(考虑异常安全性) #include <iostream>#include <vector>using namespace std;class String {public: String() : data_(new char[1]) { *data_ = '\0'; } String(const char *str) : data_(new char[strlen(str) + 1]) { strcpy(data_, str); } String(const String &rhs) : data_(new char[rhs.size() + 1]) { strcpy(data_, rhs.data_); } ~String() { delete [] data_; } String &operator=(String rhs) { // Effective C++ swap(rhs); return *this; } char &operator[](size_t index) { return data_[index]; } String &operator+=(const String &rhs) { strcat(data_, rhs.data_); return *this; } size_t size() const { return strlen(data_); } const char *c_str() const { return data_; } void swap(String &rhs) { std::swap(data_, rhs.data_); }private: char *data_;};bool operator==(const String &lhs, const String &rhs) { return strcmp(lhs.c_str(), rhs.c_str()) == 0;}bool operator!=(const String &lhs, const String &rhs) { return !(lhs == rhs);}ostream &operator<<(ostream &os, const String &rhs) { os << rhs.c_str(); return os;}String operator+(const String &lhs, const String &rhs) { String ret = lhs; ret += rhs; return ret;}int main(){ String s0 = "wor"; s0 += "ld"; String s1(s0); s0 = "hello"; cout << s0 + ", " + s1 << endl; cout << (s0 == "hello") << endl; cout << s0[1] << endl; vector<String> v; v.push_back(s0); v.push_back(s1); for (auto s : v) cout << s << endl; return 0;} 本文作者: wind4869 本文链接: https://wind4869.com/2015/04/08/string/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!