C++ Primer 第五版16章练习16.14

要求使用非类型参数定义Screen的高和宽
screen.h

#ifndef SCREEN_H
#define SCREEN_H

#include <string>
#include<vector>
using namespace std;

template <string::size_type height, string::size_type width>

class Screen;

class Window_mgr {
public:
	//窗口中每个屏幕的编号
	using PreScreen = Screen<24, 80>;
	using ScreenIndex = vector<PreScreen>::size_type;
	ScreenIndex addScreen(const PreScreen&);
	//按照编号将指定的屏幕设为空白
	void clear(ScreenIndex);
	//构造函数
	Window_mgr();
private:
	vector<PreScreen> screens;//已经初始化
};

template <string::size_type height, string::size_type width>
class Screen
{
	//友元
	friend void Window_mgr::clear(ScreenIndex);
public:
	typedef string::size_type pos;
	explicit Screen(char c=' '):cursor(0),contents(height*width,c){}

	char get() const //返回光标初的字符
	{
		return contents[cursor];
	}
	inline char get(pos ht, pos wd) const;//返回行号对应处的字符

	Screen &set(char);
	Screen &set(pos, pos, char);

	Screen &move(pos r, pos c);

	Screen &display(ostream &os)
	{
		do_display(os);
		return *this;
	}
	const Screen &display(ostream &os) const
	{
		do_display(os);
		return *this;
	}

private:
	pos cursor = 0;
	string contents;

	void do_display(ostream &os) const
	{
		os << contents;
	}
};

Window_mgr::Window_mgr() :screens{ PreScreen() } {}

template <string::size_type height, string::size_type width>
inline
Screen<height,width> &Screen<height,width>::move(pos r, pos c)
{
	pos row = r*width;
	cursor = row + c;
	return *this;
}

template <string::size_type height, string::size_type width>
inline
Screen<height, width> &Screen<height, width>::set(char c)
{
	contents[cursor] = c;
	return *this;
}

template <string::size_type height, string::size_type width>
inline
Screen<height, width> &Screen<height, width>::set(pos r, pos col, char ch)
{
	contents[r*width + col] = ch;
	return *this;
}

template <string::size_type height, string::size_type width>
char Screen<height,width>::get(pos r, pos c) const
{
	pos row = r*width;
	return contents[row + c];
}

void Window_mgr::clear(ScreenIndex i)
{
	//s是一个Screen的引用
	Screen<24,80> &s = screens[i];
	s.contents = string(24*80, ' ');
}

Window_mgr::ScreenIndex Window_mgr::addScreen(const PreScreen &s)
{
	screens.push_back(s);
	return screens.size() - 1;
}

#endif // !SCREEN_H

#pragma once

main.c调用

#include<iostream>
#include"Screen.h"

using namespace std;
int main()
{
	Screen<5, 5> myScreen('X');
	myScreen.move(4, 0).set('#').display(cout);
	cout << endl;
	myScreen.display(cout);
	cout << endl;
	system("pause");

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值