16.14 编写Screen模板

本文详细介绍了一个模板类Screen的设计与实现过程,该类用于模拟屏幕的显示效果,支持字符的读取、设置和移动光标位置等功能。Screen类采用模板参数化类型,允许用户指定位置类型的精度,提供了一系列成员函数进行屏幕内容的操作,并重载了输入输出流操作符以方便使用。

Screen.h

#pragma once
#include <iostream>
#include <string>

template <typename pos> class Screen;
template <typename pos>
std::ostream &operator<<(std::ostream &os, Screen<pos> &s);
template <typename pos>
std::istream &operator>>(std::istream &in, Screen<pos> &s);

template <typename pos>
class Screen {
    friend std::ostream &operator<<<pos>(std::ostream &os, Screen<pos> &s);
    friend std::istream &operator>><pos>(std::istream &in, Screen<pos> &s);
public:
   Screen() = default;

   Screen(pos ht, pos wd)
      : content(ht * wd, ' ') {}

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

   char get() const {
      return content[cursor];
   }

   char get(pos ht, pos wd) const;

   Screen &move(pos r, pos c);

   void accessTime() const {
      ++times;
   }

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

   const Screen &display(std::ostream &os) const {
      os << content;
      return *this;
   }

   Screen &display(std::ostream &os) {
      os << content;
      return *this;
   }

   ~Screen() {};

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

   pos cursor = 0;
   pos height = 0, width = 0;
   std::string content;

   mutable size_t times = 0;
};

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

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

template <typename pos>
Screen<pos> &Screen<pos>::set(char c) {
   content[cursor] = c;
   return *this;
}

template <typename pos>
Screen<pos> &Screen<pos>::set(pos ht, pos wd, char c) {
   content[ht * width + wd] = c;
   return *this;
}

template <typename pos>
std::ostream &operator<<(std::ostream &os, Screen<pos> &s) {
    os << "Screen heigh: " << s.height << ", Screen width: " << s.width << ", Screen curr pos: " << s.cursor << std::endl;
    return os;
}

template <typename pos>
std::istream &operator>>(std::istream &in, Screen<pos> &s) {
    in >> s.height >> s.width >> s.cursor >> s.content;
    return in;
}

main.cpp

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

int main() {
    Screen<int> s;
    std::cin >> s;
    std::cout << s;
    s.display(std::cout);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值