c++ primer 13.2.1 13.25

/*
作者:Marco
要求:c++ primer 13.2.1 13.25
特点:1.定义一个拷贝构造函数,完成vector的拷贝,而不是拷贝指针
 2.定义一个析构函数来释放vector shared_ptr可自动释放
 3.定义一个拷贝赋值运算符来释放对象当前的vector,并从右侧运算对象拷贝
 vector
*/
#include
#include"StrBlob.h"
using namespace std;
int main()
{
vector vec;
vector vec2;
StrBlob sb(vec),sb2(vec2);
vec.push_back("eeee");
vec2.push_back("rrrr");
vec = vec2;
cout << vec;
StrBlob vec3(vec2);
cout << vec3;
cout << vec2;
system("pause");
return 0;

}

//StrBlob.h
#pragma once
#include
#include
#include
using namespace std;
class StrBlob
{
friend ostream& operator << (ostream &os, const StrBlob&);
public:
using size_type = vector::size_type;
StrBlob() = default;
StrBlob(const vector &vec);
StrBlob(const StrBlob&);
bool empty()const { return data->empty(); }
void push_back(const string &t) { data->push_back(t); }
void pop_back();
StrBlob& operator = (const StrBlob&);

private:
shared_ptr> data;
void check(size_type i, const string &msg)const;
};

#include"StrBlob.h"
StrBlob::StrBlob(const vector&vec):data(new vector(vec))
{


}
StrBlob::StrBlob(const StrBlob& str)
{
auto p = *str.data;
data = make_shared>(p);
}
StrBlob& StrBlob::operator = (const StrBlob& str)
{
auto p = *str.data;
data = make_shared>(p);
return *this;
}
void StrBlob::check(size_type i,const string &msg)const
{
if (i >= data->size())
throw out_of_range(msg);
}
void StrBlob::pop_back()
{
check(0, "Can't Pop_back");
data->pop_back();
}
ostream& operator << (ostream &os, const StrBlob& str)
{
for (auto &v : *str.data)
os << v << ends;
return os;
}

你可能感兴趣的:(C++,Primer,C++,C++,primer)