C++ Primer課後練習12.2
阿新 • • 發佈:2019-01-30
//練習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; }