12.19
拿此题来说,StrBlobPtr类要用到StrBlob类,而StrBlob类要用到StrBlobPtr类。
即如下:
class StrBlob{
friend class StrBlobPtr;
public:
typedef std::vector<std::string>::size_type size_type;
StrBlob();//默认构造函数
StrBlob(std::initializer_list<std::string>);//接收1个参数的initializer_list作为形参
size_type size() const { return data->size(); }
bool empty() const { return data->empty(); }
void push_back(const std::string &t) { return data->push_back(t); }
void pop_back();
std::string& front();
std::string& back();
StrBlobPtr begin() { return StrBlobPtr(*this); }//返回一个指向首元素的迭代器
StrBlobPtr end(){ auto ret = StrBlobPtr(*this, this->size()); return ret; }//返回尾后的迭代器
private:
std::shared_ptr<std::vector<std::string>> data;//一个指向vector<string>的智能指针
void check(size_type i, const std::string &msg) const;//检查data[i]是否合法,抛出异常
};
class StrBlobPtr{
public:
StrBlobPtr() :curr(0) { }//默认构造函数,令curr为0
StrBlobPtr(StrBlob &a, size_t t = 0) :wptr(a.data), curr(t) { }//带参数的构造函数
string & deref() const;//解引用操作
StrBlobPtr & incr();//递增操作
private:
shared_ptr<vector<string>> check(size_t, const string&) const;//检查下标是否过界
weak_ptr<vector<string>> wptr;//定义一个空的weakptr
size_t curr;//定义元素下标
};
可以看到这两个类要相互包含,那么该怎样处理?
1.如果两个都在各自的.h中,并且相互包含对方的.h,不用前置声明。
即在StrBlob.h文件中 #include "StrBlobPtr.h" 在StrBlobPtr.h文件中 #include "StrBlob.h"