解决方案是将std::string的所有操作都显式地公开给新包装器,并将它们重定向到std::string的对应操作,示例代码如下:
class MyString {
public:
// construct from const char*
MyString(const char* str) : str_(str) {}
// copy constructor
MyString(const MyString& other) : str_(other.str_) {}
// move constructor
MyString(MyString&& other) noexcept : str_(std::move(other.str_)) {}
// copy assignment
MyString& operator=(const MyString& other) {
str_ = other.str_;
return *this;
}
// move assignment
MyString& operator=(MyString&& other) noexcept {
str_ = std::move(other.str_);
return *this;
}
// conversion to std::string
operator const std::string&() const noexcept {
return str_;
}
// length() operation
size_t length() const noexcept {
return str_.length();
}
// find() operation
size_t find(const MyString& substr, size_t pos = 0) const noexcept {
return str_.find(substr.str_, pos);
}
// substr() operation
MyString substr(size_t pos = 0, size_t len = std::string::npos) const {
return MyString(str_.substr(pos, len).c_str());
}
// insert() operation
MyString& insert(size_t pos, const MyString& str) {
str_.insert(pos, str.str_);
return *this;
}
// erase() operation
MyString& erase(size_t pos, size_t len = std::string::npos) {
str_.erase(pos, len);
return *this;
}
// append() operation
MyString& operator+=(const MyString& str) {
str_.append(str.str_);
return *this;
}
private:
std::string str_;
};