C++ primer 第五版 中文版 练习 12.19 个人code

来源:互联网 发布:淘宝上架时间周期 编辑:程序博客网 时间:2024/06/05 18:02

C++ primer 第五版 中文版 练习 12.19 

题目:定义你自己版本的StrBlobPtr,更新StrBlob类,加入恰当的friend声明及begin和end成员。

答:

写这两个类的时候碰着两个问题:“fatal error C1014: 包含文件太多 : 深度 = 1024”  这个出现的原因是:我之前把两个类放在了两个头文件里声明

然后互相包含出现了该问题。

后来改成现在这样把两个类定义在同一个头文件里,就没有这问题了,但一直提示“StrBlob 未标识的类型“我就不知道怎么回事了,百度了下相关问题

发现跟 变量要用没有事先声明的错误差不多,就在 StrBlobPtr 类之前声明了下 StrBlob类,然后把函数定义放在源文件中去定义,问题解决了。

下面是完整能用的代码:

头文件:文件名为:mypractice_12_19.h

/*定义两个类 : StrBlobPtr、StrBlob */#include <memory>#include <vector>#include <string>class StrBlob;  class StrBlobPtr{public:friend class StrBlob;StrBlobPtr() :curr(0){}StrBlobPtr(StrBlob &a, size_t sz = 0); //这个一定要放在定义文件中去定义,不然会出现 “error C2027: 使用了未定义类型“StrBlob”错误和。std::string& deref() const;StrBlobPtr& incr();private:std::shared_ptr<std::vector<std::string>> check(std::size_t, const std::string&) const;std::weak_ptr<std::vector<std::string>> wptr;std::size_t curr;};class StrBlob{public:friend class StrBlobPtr;typedef std::vector<std::string>::size_type size_type;//  下面这个等同于上面这个。//using size_type = std::vector<std::string>::size_type; StrBlob();StrBlob(std::initializer_list<std::string> il);size_type size() const { return data->size(); }bool empty() const { return data->empty(); }//添加和删除元素void push_back(const std::string &t) { data->push_back(t); }void pop_back();//元素访问std::string& front();std::string& back();StrBlobPtr begin() { return StrBlobPtr(*this); }StrBlobPtr end(){auto ret = StrBlobPtr(*this, data->size());return ret;}private:std::shared_ptr<std::vector<std::string>> data;//如果data[i]不合法,抛出一个异常。void check(size_type i, const std::string &msg) const;};

源文件:文件名:mypractice_12_19.cpp

#include "mypractice_12_19.h"using namespace std;//定义构造函数StrBlob::StrBlob() :data(make_shared<vector<string>>()){}StrBlob::StrBlob(initializer_list<string> il) : data(make_shared<vector<string>>(il)){}void StrBlob::check(size_type i, const string &msg) const{if (i >= data->size())throw out_of_range(msg);}string& StrBlob::front(){check(0, "front on empty StrBlob");return data->front();}string& StrBlob::back(){check(0, "back on empty StrBlob");return data->back();}void StrBlob::pop_back(){check(0, "pop_back on empty StrBlob");data->pop_back();}StrBlobPtr::StrBlobPtr(StrBlob &a, size_t sz) :wptr(a.data), curr(sz){}std::shared_ptr<std::vector<std::string>> StrBlobPtr::check(std::size_t i, const std::string &msg) const{auto ret = wptr.lock();if (!ret)throw std::out_of_range(msg);return ret;}std::string& StrBlobPtr::deref() const{auto p = check(curr, "dereference past end");return (*p)[curr];}StrBlobPtr& StrBlobPtr::incr(){check(curr, "increment past end of StrBlobPtr");++curr;return *this;}



0 0
原创粉丝点击