C++ Primer 第五版 中文版 练习 13.26

来源:互联网 发布:手机视频搞怪软件 编辑:程序博客网 时间:2024/06/03 13:00

C++ Primer 第五版 中文版 练习 13.26

题目: 对上一题中描述的StrBlob类,编写你自己的版本。

StrBlob.h

[cpp] view plain copy
  1. #pragma once  
  2. #include <memory>  
  3. #include <vector>  
  4. #include <string>  
  5. #include "StrBlobPtr.h"  
  6.   
  7.   
  8. class StrBlob  
  9. {  
  10. public:  
  11.     friend class StrBlobPtr;  
  12.     typedef std::vector<std::string>::size_type size_type;  
  13.     //  下面这个等同于上面这个。  
  14.     //  using size_type = std::vector<std::string>::size_type;   
  15.   
  16.     StrBlob();  
  17.     StrBlob(std::initializer_list<std::string> il);  
  18.     //拷贝构造函数  
  19.     StrBlob(const StrBlob&);  
  20.     //拷贝赋值运算符  
  21.     StrBlob& operator=(const StrBlob&);  
  22.     size_type size() const { return data->size(); }  
  23.     bool empty() const { return data->empty(); }  
  24.     //添加和删除元素  
  25.     void push_back(const std::string &t) { data->push_back(t); }  
  26.     void pop_back();  
  27.     //元素访问  
  28.     std::string& front();  
  29.     std::string& back();  
  30.   
  31.     StrBlobPtr begin() { return StrBlobPtr(*this); }  
  32.     StrBlobPtr end()  
  33.     {  
  34.         auto ret = StrBlobPtr(*this, data->size());  
  35.         return ret;  
  36.     }  
  37.   
  38. private:  
  39.     std::shared_ptr<std::vector<std::string>> data;  
  40.     //如果data[i]不合法,抛出一个异常。  
  41.     void check(size_type i, const std::string &msg) const;  
  42. };  
StrBlob.cpp

[cpp] view plain copy
  1. #include "StrBlob.h"  
  2.   
  3. using namespace std;  
  4.   
  5. //定义构造函数  
  6. StrBlob::StrBlob() :data(make_shared<vector<string>>())  
  7. {  
  8.   
  9. }  
  10.   
  11. StrBlob::StrBlob(initializer_list<string> il) : data(make_shared<vector<string>>(il))  
  12. {  
  13.   
  14. }  
  15.   
  16. //定义拷贝构造函数  
  17. StrBlob::StrBlob(const StrBlob &SB) :data(make_shared<vector<string>>(SB.data))  
  18. {  
  19.   
  20. }  
  21. //定义拷贝赋值运算符  
  22. StrBlob& StrBlob::operator=(const StrBlob &SB)  
  23. {  
  24.     auto newdata = shared_ptr<vector<string>>(SB.data);  
  25.     data = newdata;  
  26.     return *this;  
  27. }  
  28.   
  29. void StrBlob::check(size_type i, const string &msg) const  
  30. {  
  31.     if (i >= data->size())  
  32.         throw out_of_range(msg);  
  33. }  
  34.   
  35. string& StrBlob::front()  
  36. {  
  37.     check(0, "front on empty StrBlob");  
  38.     return data->front();  
  39. }  
  40.   
  41. string& StrBlob::back()  
  42. {  
  43.     check(0, "back on empty StrBlob");  
  44.     return data->back();  
  45. }  
  46.   
  47. void StrBlob::pop_back()  
  48. {  
  49.     check(0, "pop_back on empty StrBlob");  
  50.     data->pop_back();  
  51. }  
0 0
原创粉丝点击