C++ 隐含的this 指针

c++primer   页数:376-379 备份, 很有嚼头

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class Screen
{
    public:
        typedef string::size_type index;
        Screen(index r, index c) : row(r), col(c), contents(r * c, 0) {};
        Screen& set(index r, index c, char val);
        Screen& set(char val);
        Screen& move(index r, index c);
        Screen& display();
        const Screen& display() const;
    private:
        string contents;
        index cursor;
        index row, col;
        void do_display() const
        { cout << contents << endl;}

};

Screen& Screen::set(index r, index c, char val)
{
    contents[r * col + c] = val;
    return *this;
}

Screen& Screen::set(char val)
{
    contents[cursor] = val;
    return *this;
}

Screen& Screen::move(index r, index c)
{
    cursor = r * col + c;
    return *this;
}

Screen& Screen::display()
{
    do_display();
    cout << "not const" << endl;
    return *this;
}

const Screen& Screen::display() const 
{
    do_display();
    cout << "const" << endl;
    return *this;
}

int main()
{
    Screen s(3, 4);
    s.set(0, 0, 'a');
    s.set(0, 1, 'b').set(0, 2, 'c').display();
    const Screen mys(4, 5);
    mys.display();

    return 0;
}

 

posted @ 2013-12-02 22:41  jihite  阅读(863)  评论(0编辑  收藏  举报