C++Primer12.1.1节练习

练习12.1:

b1包含4个元素,b2也包含4个元素,b1和b2共享一个StrBlob对象

练习12.2:

#include <iostream>
#include <memory>
#include <vector>
using namespace std;


class StrBlob {
public:
	typedef std::vector<std::string>::size_type size_type;
	StrBlob();
	StrBlob(std::initializer_list<std::string>il);
	size_type size()const { return data->size(); }
	bool empty()const { return data->empty(); }
	void push_back(const std::string& t) { data->push_back(t); }
	void pop_back();
	std::string& front()const;
	std::string& back()const;

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


StrBlob::StrBlob():data(make_shared<vector<string>>()){ }
StrBlob::StrBlob(initializer_list<string>il):data(make_shared<vector<string>>(il)){ }


void StrBlob::check(size_type i, const string& msg)const
{
	if (i >= data->size())
	{
		throw out_of_range(msg);
	}
}

string& StrBlob::front()const
{
	check(0, "front on empty StrBlob");
	return data->front();
}

string& StrBlob::back()const
{
	check(0, "back on empty StrBlob");
	return data->back();
}

void StrBlob::pop_back()
{
	check(0, "pop_back on empty StrBlob");
	data->pop_back();
}


int main()
{
	system("pause");
	return 0;
}

练习12.3:

不需要,push_back和pop_back会增加或者减小StrBlob共享的vector,即StrBlob的数据成员所指向的内容会发生改变,所以不能用const

练习12.4:

i 是 size_type类型的,是vector<string>::size_type的别名,是unsigned类型的数据,大于等于0

练习12.5:

定义explicit显式构造函数使得构造更加清晰,防止一些我们不希望看到的隐式转换发生。缺点是程序不那么灵活了,无法发生隐式转换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白学C++.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值