CPP PRIMER中的一道非类型模板参数的题目
CPP PRIMER中的一道非类型模板参数的题目,编写一个SCREEN类模板,并为其编写输出操作符.
以下是我写的程序:
前向声明:
template <int,int> class Screen;
重载输出操作符:
template <int hi, int wid>
ostream& operator < < (ostream &os, const Screen <hi,wid> &sc)
{
for(string::size_type outer_index=0; outer_index!=sc.height;++outer_index)
{
for(string::size_type inner_index=0; inner_index!=sc.width;++inner_index)
cout < <sc.screen[outer_index*sc.height + sc.width];
cout < <endl;
}
return os;
}
SCREEN模板的定义:
template <int hi, int wid>
class Screen {
friend ostream& operator < < <hi,wid> (ostream&,const Screen&);
public:
// template nontype parameters used to initialize data members
Screen(): screen(hi*wid, '# '), cursor(0),
height(hi), width(wid) { }
private:
string screen;
string::size_type cursor;
string::size_type height, width;
};
我的想法是把SCREEN的内容按高宽的比例输出,但是输出操作符却有一些问题:
1.对某些实例化的SCREEN对象可以正常输出,例如Screen <2,7> scr1;但是将实参改为 <1,7> 或者 <7,7> 时便会出现最后一行不输出的问题,将实参改为 <16,9> 时后面几行的内容又不是 '# ',这是为什么?
2.我感觉我的重载输出符的声明方式有些不妥,但又说不上来,非类型模板的类出现在其他函数的参数表中时一定要确定模板参数的值吗?
请高手指教...
[解决办法]
因为ostream& operator < < (ostream &os, const Screen <hi,wid> &sc) 里那个循环不对
导致sc.screen[outer_index*sc.height + sc.width]; 越界了