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

来源:互联网 发布:gprs数据采集器 编辑:程序博客网 时间:2024/06/03 06:26
#include <iostream>#include <string>class Screen{public:    using pos = std::string::size_type;    Screen() = default;    Screen(pos ht, pos wd, char c):height(ht),width(wd),contents(ht*wd,c){}    Screen& display(std::ostream &os)    {        do_display(os);        return *this;    }    const Screen& display(std::ostream &os) const//调用do_display输出字符串    {        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;}//用于输出字符串    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;}


测试代码:

#include "Screen.h"#include <iostream>using std::cout;using std::endl;int main(){    Screen myScreen(5,5,'X');    myScreen.display(cout);    cout << endl;    cout << endl;    myScreen.move(4,0).set('#').display(cout);    cout << endl;    return 0;}


1 0