要求使用非类型参数定义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;
}