C++ Primer(第五版)练习7.23 7.27 7.32

#include<iostream>
#include<string>
#include<vector>

using namespace std;

class Screen;
class Window_mgr
{
private:
	vector<Screen> screens;
public:
	using Screen_index = vector<Screen>::size_type;

	void clear(Screen_index i);
	Window_mgr() = default;
};

class Screen
{
	friend void Window_mgr::clear(Screen_index i);
public:
	using pos = string::size_type;
	mutable unsigned counter = 0;

	//constructors
	Screen() = default;
	Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht*wd, c) {}

	//operations
	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);

	//output methods
	Screen &display(ostream &os) { do_display(os); return *this; }
	const Screen &display(ostream &os) const { do_display(os); return *this; }
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	string contents;
	void do_display(ostream &os) const { os << contents; }
};

char Screen::get(pos r, pos c) const
{
	return contents[r*width + c];
}

inline Screen &Screen::move(pos r, pos c)
{
	cursor = r*width + c;
	return *this;
}

inline Screen &Screen::set(char c)
{
	contents[cursor] = c;
	return *this;
}

inline Screen &Screen::set(pos r, pos c, char ch)
{
	contents[r*width + c] = ch;
	return *this;
}

void Window_mgr::clear(Screen_index i)
{
	Screen &s = screens[i];
	s.contents = string(s.height*s.width, ' ');
}

int main(int argc, char *argv[])
{
	//some operations omitted ...
	system("pause");
	return 0;
}



对于成员函数作为友元的依赖关系:

1、先定义Window_mgr类,其中声明clear函数,但不能定义它。在clear使用Screen的成员之前必须先声明clear。

2、接下来定义Screen,其中包括对于clear的友元声明。

3、最后定义clear,此时它才可以使用Screen的成员。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值