第七章 习题7-21-习题7-30

习题7-21-习题7-22

这个看你需要设置,只要记住两个知识点:

1、struct与class默认权限不同;

2、private数据成员一般只能由类的函数访问,外部函数无法访问;public数据成员则都可以访问;

习题7-23-习题7-24

class Screen {
public:
	typedef std::string::size_type pos;
	Screen() = default;
	Screen(pos ht,pos wd,char c):height(ht),width(wd),contents(' '){}
	Screen(pos ht,pos wd,char c):height(ht),width(wd),contents(ht*wd,c){}
	char get()const
	{
		return contents[cursor];
	}
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	std::string contents;
};

习题7-25

P239页 7.1.5 能安全的使用拷贝和赋值操作,但是不能分配内存;

习题7-26

inline double avg_price() const { return units_sold ? revenue/units_sold : 0; }

习题7-27

#include <iostream>
#include<string>
using namespace std;
class Screen {
public:
	typedef std::string::size_type pos;
	Screen() = default;
	Screen(pos ht, pos wd) :height(ht), width(wd), contents(ht*wd, ' ') {}
	Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht*wd, c) {}
	char get()const
	{
		return contents[cursor];
	}
	inline char get(pos ht, pos wd) const;
	Screen &move(pos r, pos c);
	Screen &set(char);
	Screen &set(pos, pos, char);
	Screen &display(std::ostream &os)
	{
		do_display(os); return *this;
	}
	const Screen &display(std::ostream &os) const
	{
		do_display(os); return *this;
	}
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	std::string contents;
	void do_display(std::ostream &os)const { os << contents; }
};
inline Screen &Screen::move(pos r, pos c)
{
	pos row = r*width;
	cursor = row + c;
	return *this;
}
char Screen::get(pos r, pos c) const
{
	pos row = r*width;
	return contents[row + c];
}
inline Screen &Screen::set(char c)
{
	contents[cursor] = c;
	return *this;
}
inline Screen&Screen::set(pos r, pos col, char ch)
{
	contents[r*width + col] = ch;
	return *this;
}
void main()
{
	Screen myScreen(5, 5, 'X');
	myScreen.move(4, 0).set('#').display(cout);
	cout << "\n";
	myScreen.display(cout);
	cout << "\n";
}

习题7-28

由于使用的事类的副本,所以不会改变原来的类,第二行作用在副本上;

习题7-29

输出为:

引用输出:
XXXXX XXXXX XXXXX XXXXX #XXXX
XXXXX XXXXX XXXXX XXXXX #XXXX

非引用输出:
XXXXX XXXXX XXXXX XXXXX #XXXX
XXXXX XXXXX XXXXX XXXXX XXXXX

习题7-30

这个是照着答案抄的。。。

优点:

1、使程序意图明确,更易读;

2、可以使形参名和要赋值的成员名相同。

如:std::string& setName(const string& name) { this->name = name; }

缺点:有些场景下比较多余

std::string const& getName() const { return this->name; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值