#include <iostream>
#include <string>
using namespace std;
class Screen
{
public:
typedef string::size_type index;
char get() const
{
return contents[cursor];
}
inline char get(index r,index c) const;
index get_cursor() const;
Screen(index hght,index wght,const string &cntnts);
/*以下成员函数的返回类型是Screen&,指明该成员函数返回对其自身
类类型的对象的引用,即每个函数都返回调用自己的那个对象*/
Screen& move(index r,index c);
Screen& set(char);
Screen& display(ostream &os);
private:
std::string contents;
index cursor;
index height,width;
};
Screen::Screen(index hght,index wdth,const string &cntnts):
contents(cntnts),cursor(0),height(hght),width(wdth)
{}
char Screen::get(index r,index c) const
{
index row = r*width;
return contents[row + c];
}
/*index属于Screen类,类外使用,必须加“::“*/
Screen::index Screen::get_cursor() const
{
return cursor;
}
Screen& Screen::move(index r,index c)
{
index row = r * width;
cursor = row + c;
return *this;
}
Screen& Screen::set(char c)
{
contents[cursor] = c;
return *this;
}
Screen& Screen::display(ostream &os)
{
os << contents;
return *this;
}
int main(int argc,char *argv[])
{
/*根据屏幕的高度,宽度和内容的值来创建Screen*/
Screen myScreen(5,6,"aaaaa\naaaaa\naaaaa\naaaaa\naaaaa\n");
/*将光标移至指定位置,设置字符并显示屏幕内容*/
myScreen.move(4,0).set('#').display(cout);
return 0;
}
|