C++ Primer(第5版) 练习 7.29
练习 7.29 修改你的Screen类,令move、set和display函数返回Screen并检查程序的运行结果,在上一个练习中你的推测正确吗?
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
/*************************************************************************> File Name: ex7.29.cpp> Author: > Mail: > Created Time: Thu 15 Feb 2024 09:18:54 PM CST************************************************************************/#include<iostream>
using namespace std;class Screen{public:using pos = string::size_type;Screen() = default;Screen(pos ht, pos wd): height(ht), width(wd), contents(20, ' ') {}Screen(pos ht, pos wd, char c): height(ht), width(wd), contents(ht * wd, c) {}char get() const;char get(pos ht, pos wd) const;Screen move(pos r, pos c);Screen set(char c);Screen set(pos ht, pos wd, char c);Screen display(ostream &output);const Screen display(ostream &output) const;private:void do_display(ostream &output) const { output<<contents; }pos cursor = 0;pos height = 0;pos width = 0;string contents;
};inline char Screen::get() const{return contents[cursor];
}inline char Screen::get(pos ht, pos wd) const{pos row = ht * width;return contents[row + wd];
}inline Screen Screen::move(pos r, pos c){pos row = r * width;cursor = row = c;return *this;
}inline Screen Screen::set(char c){contents[cursor] = c;return *this;
}inline Screen Screen::set(pos ht, pos wd, char c){contents[ht * width + wd] = c;return *this;
}inline Screen Screen::display(ostream &output){do_display(output);return *this;
}inline const Screen Screen::display(ostream &output) const{do_display(output);return *this;
}int main(){Screen myScreen(5, 5, 'X');myScreen.move(4, 0).set('#').display(cout);cout<<"\n";myScreen.display(cout);cout<<"\n";return 0;
}