C++ Primer课后练习12.2


//练习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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值