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

被折叠的 条评论
为什么被折叠?



