马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
#include <string>
#include <cstdlib>
class Screen {
public:
typedef std::string::size_type pos_t;
Screen() = default;
Screen(pos_t w, pos_t h, char c):
width(w), height(h), contents(h * w, c) {}
char get() const {
return contents[cursor];
}
char get(pos_t x, pos_t y) const;
Screen &set(char c);
Screen &set(pos_t x, pos_t y, char ch);
Screen &move(pos_t x, pos_t y);
Screen &display(std::ostream &os) {
do_display(os);
return *this;
}
const Screen &display(std::ostream &os) const {
do_display(os);
return *this;
}
private:
pos_t cursor = 0;
pos_t height = 0, width = 0;
std::string contents;
const Screen &do_display(std::ostream &os) const;
pos_t get_index(pos_t x, pos_t y) const {
if (x < width || y < height)
return y * width + x;
std::cerr << "错误:数组越界" << std::endl;
exit(EXIT_FAILURE);
}
};
char Screen::get(pos_t x, pos_t y) const {
return contents[get_index(x, y)];
}
Screen &Screen::move(pos_t x, pos_t y) {
cursor = get_index(x, y);
return *this;
}
Screen &Screen::set(char c) {
contents[cursor] = c;
return *this;
}
Screen &Screen::set(pos_t x, pos_t y, char c) {
contents[get_index(x, y)] = c;
return *this;
}
const Screen &Screen::do_display(std::ostream &os) const {
for (int x = 0; x != width; ++x) {
for (int y = 0; y != height; ++y)
os << get(x, y);
os << std::endl;
}
return *this;
}
int main(void) {
Screen myScreen(5, 5, 'X');
myScreen.set(4, 0, '#');
myScreen.set(4, 4, '#');
myScreen.display(std::cout);
std::cout << '\n';
return 0;
}
输出:XXXXX
XXXXX
XXXXX
XXXXX
#XXX#
但正确的输出应该是XXXX#
XXXXX
XXXXX
XXXXX
XXXX#
我该如何修改程序? |