c++ primer 5th中,7.3.1节引入的screen类,其中有个代码是获取指定位置光标的值,但是计算出来之后,和输入的参数有误差。
新手刚刚开始,求解答!谢谢谢
就是下列代码的第二个get和move函数,实际上得到的光标和要求的光标位置差了一行
例如初始化的screen是4,6,c 然后调用get求2,3坐标的值,虽然都是c,但是光标实际的位置不是在第三行上吗,并不是在我所要求的第二行上
class Screen{
public:
using pos = std::string::size_type;
Screen() = default;
Screen(pos h , pos w) : height(h) , width(w) , contents(h*w , ' ') { }
Screen(pos h , pos w , char ch) : height(h) , width(w) , contents(h*w , ch) { }
//定义屏幕的尺寸和内容的构造函数
char get() const //读取当前光标的字符
{
return contents[cursor]; //隐式内联
}
inline char get(pos ht , pos wd) const; //显示的内联,读取光标字符
Screen & move(pos r , pos c); //移动光标
private:
std::string contents;
pos cursor = 0;
pos height = 0 , width = 0;
};
inline
Screen & Screen :: move(pos r , pos c)
{
pos row = r * width;
cursor = row + c;
return *this;
}
char Screen :: get(pos r , pos c) const
{
pos row = r * width;
return contents[ row + c ];
}