您的位置:首页 > 编程语言 > C语言/C++

c++ primer 第五版 Screen类(包含Window_mgr类)

2016-04-06 20:40 435 查看
#include <iostream>
#include <string>
#include <vector>

class Screen
{
public:
using pos = std::string::size_type;

friend class Window_mgr;//声明友元

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

Screen& display(std::ostream &os)//基于const的重载
{
do_display(os);
return *this;
}
const Screen& display(std::ostream &os) const//基于const的重载
{
do_display(os);
return *this;
}

Screen& set(char);//设置光标处字符
Screen& set(pos, pos, char);//设置给定位置处字符
char get() const//返回光标处字符
{
return contents[cursor];
}
char get(pos ht, pos wd) const;//返回给定位置处字符
Screen& move(pos r, pos c);//将光标移动到指定位置

private:
void do_display(std::ostream &os) const {os << contents << std::endl;}

mutable size_t access_ctr = 0;
pos cursor = 0;//光标的位置
pos height = 0,width = 0;//屏幕的高度和宽度
std::string contents;//存储光标所在位置的字符
};

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

inline 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;
}

class Window_mgr
{
public:
using ScreenIndex = std::vector<Screen>::size_type;//窗口中每个屏幕的编号
void clear(ScreenIndex);//按照编号将指定的Screen重置为空白
void show();//输出屏幕
ScreenIndex addScreen(const Screen&);//增加屏幕
private:
std::vector<Screen> screens{Screen(24,80,'*')};//默认情况下,一个Window_mgr包含一个全是‘*’的Screen
};

void Window_mgr::show()
{
for(auto &temp : screens)
temp.display(std::cout);
}

Window_mgr::ScreenIndex Window_mgr::addScreen(const Screen &s)
{
screens.push_back(s);
return screens.size()-1;//向窗口添加1个Screen,返回他的编号
}

void Window_mgr::clear(ScreenIndex i)
{
Screen &s = screens[i];
s.contents = std::string(s.height*s.width,' ');
}
测试代码:
#include "Screen.h"#include <iostream>using std::cout;using std::endl;int main(){int count;Window_mgr Screens;Screen myScreen(5,5,'X');count = Screens.addScreen(myScreen);Screens.show();cout << "myScreen的编号:" << count << endl;return 0;}运行结果:
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: