C++ Primer课后练习12.2

来源:互联网 发布:ipad绿色上网软件 编辑:程序博客网 时间:2024/06/07 01:13
//练习12.2#include#include #include #include #include #include using namespace std;class StrBlob {public:using size_type = vector::size_type;StrBlob() : data(std::make_shared<vector>()) {cout << "你使用了默认重载" << endl;}StrBlob(std::initializer_list il): data(std::make_shared<vector>(il)){cout << "你使用了带参数的构造器" << endl;}size_type size(){return data->size();}size_type size() const {cout << "你使用了size这个类成员函数" << endl; return data->size();}bool empty() const { return data->empty(); }void push_back(const string& t) { data->push_back(t); }void pop_back(){check(0, "pop_back on empty StrBlob");data->pop_back();}std::string& front(){check(0, "front on empty StrBlob");return data->front();}std::string& back(){check(0, "back on empty StrBlob");return data->back();}const std::string& front() const{check(0, "front on empty StrBlob");cout << "你使用了常量front函数" << endl;return data->front();}const std::string& back() const{check(0, "back on empty StrBlob");cout << "你使用了常量back函数" << endl;return data->back();}private:void check(size_type i, const string& msg) const{if (i >= data->size()) throw std::out_of_range(msg);}private:std::shared_ptr<vector> data;//data是一个智能指针,指向what what ;};int main(void){StrBlob b1;//调用默认构造函数{StrBlob b2 = { "a", "an", "the" };//调用带参数的构造函数b1 = b2;//赋值,拷贝b2.push_back("about");cout << b2.size() << endl;}cout << b1.size() << endl;cout << b1.front() << " " << b1.back() << endl;const StrBlob b3 = b1;cout << b3.front() << " " << b3.back() << endl;}
0 0