#include <iostream> #include <string> using namespace std; class Person { public: Person(const std::string &nm, const std::string &addr) { this->address = addr; this->name = nm; } std::string getName()const { return this->name; // this是指针隐含的指针可以省略,指向当前的对象, } std::string getAddress() const { return this->address; } private: std::string name; std::string address; }; class Screen // 屏幕上的窗口 { public: typedef std::string::size_type index; Screen(index ht = 0, index wd = 0) :contents(ht*wd, 'C'), cursor(0), height(ht), width(wd), access_ctr(0) {} char get() const { return contents[cursor]; } char get(index r, index c) const { index row = r * width; return contents[row + c]; } Screen& move(index r, index c); Screen& set(index, index, char); Screen& set(char); const Screen& display(std::ostream &os) const { ++access_ctr; do_display(os); return *this; } Screen& display(std::ostream &os) { ++access_ctr; do_display(os); return *this; } private: std::string contents; index cursor; index height, width; mutable size_t access_ctr; // 计数. mutable是一个可变的可对const进行修改, void do_display(std::ostream &os) const { os << contents; } }; Screen& Screen::set(index r, index c, char ch) { index row = r*width; contents[row + c] = ch; return *this; } Screen& Screen::set(char c) { contents[cursor] = c; return *this; } Screen& Screen::move(index r, index c) { index row = r * width; cursor = row + c; return *this; } int main() { Person p("小崔", "九龙路与王城大道"); cout << p.getName() << endl; Screen myScreen(5, 3); cout << myScreen.get() << endl; myScreen.set(3, 2, 'U'); cout << myScreen.get(3, 2) << endl; // 这两行是重点, /*myScreen.move(2, 3); myScreen.set('I');*/ //跟简单的写法, myScreen.move(2, 3).set('I').display(cout).set('L').display(cout); cout << endl; myScreen.move(4, 0).set('A').move(4, 1).set('B').move(4, 2).set('C').display(cout); cout << endl; cout << myScreen.get() << endl; //myScreen.display(cout); cout << endl; return 0; }