#include <iostream> #include <string> using namespace std; class Screen { public: typedef std::string::size_type index; // 用index代替所有的std::string::size_type就是使用类型别名简化类, Screen(index ht = 0, index wd = 0) :contents(ht * wd, 'X'), cursor(0), height(ht), width(wd) { } Screen(index ht, index wd, const std::string &conts); char get() const; // get() 是成员函数是可以被重载的,函数声明在类的内部, /*{ return contents[cursor]; }*/ //char get(std::string::size_type r, std::string::size_type c) const inline char get(index r, index c) const; /*{ index row = r * width; return contents[row + c]; }*/ private: std::string contents; index cursor; // cursor 是光标的位置, index height,width; }; Screen::Screen(index ht, index wd, const std::string &conts) :contents(conts), cursor(0), height(ht), width(wd) {} inline char Screen::get() const // 函数的定义在类的外部,显示指定inline 成员函数, { return contents[cursor]; } char Screen::get(index r, index c) const { index row = r * width; return contents[row + c]; } int main() { Screen a(10,100); cout << a.get() << endl; cout << a.get(2, 7) << endl; cout << endl; Screen b(3, 6, "hello xiaoo cuicui"); cout << b.get() << endl; cout << b.get(2, 4) << endl; Screen::index ind; cout << "小崔,生日快乐。" << endl; return 0; }