-
Notifications
You must be signed in to change notification settings - Fork 33
/
7.29.cpp
76 lines (65 loc) · 2.07 KB
/
7.29.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* Exercise 7.29: Revise your Screen class so that move, set, and display
* functions return Screen and check your prediction from the previous
* exercise.
*
* By Faisal Saadatmand
*/
#include <iostream>
#include <string>
class Screen {
public:
using pos = std::string::size_type;
Screen() = default;
Screen(pos ht, pos wd, char c) : height(ht), width(wd),
contents(ht * wd, c) {}
Screen(pos ht, pos wd) : height(ht), width(ht),
contents(ht * wd, ' ') {}
// members
Screen display(std::ostream &os)
{ do_display(os); return *this; }
const Screen display(std::ostream &os) const
{ do_display(os); return *this; }
Screen set(char);
Screen set(pos, pos, char);
char get() const // get the character at the cursor
{ return contents[cursor]; } // implicitly inline
inline char get(pos ht, pos wd) const; // explicitly inline
Screen move(pos r, pos c); // can be made inline later
private:
void do_display(std::ostream &os) const {os << contents;}
pos cursor{0};
pos height{0};
pos width{0};
std::string contents;
};
inline Screen Screen::set(char c)
{
contents[cursor] = c; // set the new value at the current cursor location
return *this; // return this object as an lvalue
}
inline Screen Screen::set(pos r, pos col, char ch)
{
contents[r * width + col] = ch; // set specified location to given value
return *this;
}
inline Screen Screen::move(pos r, pos c)
{
pos row = r * width; // compute the row location
cursor = row + c; // move cursor to the column within that raw
return *this; // return this object as an lvalue
}
char Screen::get(pos r, pos c) const // declared as inline in the class
{
pos row = r * width; // compute row location
return contents[row + c]; // return character at the given column
}
int main()
{
Screen myScreen(5, 5, 'X');
myScreen.move(4, 0).set('#').display(std::cout);
std::cout << "\n";
myScreen.display(std::cout);
std:: cout << "\n";
return 0;
}