设计一个KString类,有两个私有成员,要求实现移动构造,用上shareed_ptr实现写时拷贝
时间: 2024-06-11 15:05:14 浏览: 9
以下是一个可能的KString类的实现:
```c++
#include <memory>
#include <string>
class KString {
public:
KString() = default;
explicit KString(const std::string& str)
: data_{std::make_shared<std::string>(str)} {}
KString(const KString& other)
: data_{other.data_} {}
KString(KString&& other) noexcept
: data_{std::move(other.data_)} {}
KString& operator=(const KString& other) {
data_ = other.data_;
return *this;
}
KString& operator=(KString&& other) noexcept {
data_ = std::move(other.data_);
return *this;
}
const char* c_str() const {
return data_->c_str();
}
size_t size() const {
return data_->size();
}
bool empty() const {
return data_->empty();
}
const std::string& str() const {
return *data_;
}
bool operator==(const KString& other) const {
return *data_ == *other.data_;
}
bool operator!=(const KString& other) const {
return !(*this == other);
}
char operator[](size_t index) const {
return (*data_)[index];
}
friend std::ostream& operator<<(std::ostream& os, const KString& str) {
os << *str.data_;
return os;
}
private:
std::shared_ptr<std::string> data_;
};
```
这个KString类包含两个私有成员:一个是`std::shared_ptr<std::string>`类型的指针`data_`,另一个是默认构造函数。
`KString`类有三个构造函数:一个是默认构造函数,一个是接受`std::string`类型参数的构造函数,另一个是接受另一个`KString`对象的构造函数。构造函数中用`std::shared_ptr`来保存字符串数据,可以实现写时拷贝。`KString`对象的复制构造函数和赋值运算符都使用了`std::shared_ptr`的拷贝和赋值语义。移动构造函数和移动赋值运算符也使用了`std::shared_ptr`的移动语义。
`KString`类还有一些常用的成员函数,比如`c_str()`、`size()`、`empty()`和`str()`等,它们都是对`std::string`的包装。
`KString`类重载了`operator==`、`operator!=`和`operator[]`,还提供了一个友元函数`operator<<`,用于方便地输出`KString`对象。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)