注意:
inline 定义的函数必须放在 .h 文件中,否则编译器报错! 其次,注意写全称在 .h 里,如 std::
screen.h 头文件
#ifndef SCREEN_H
#define SCREEN_H
#include<string>
#include<iostream>
class Screen
{
public:
typedef std
::string
::size_type index
;
Screen(index hgth
, index wdth
, const std
::string
&cntnts
);
char get() const { return contents
[cursor
];}
char get(index ht
, index wd
) const;
index
get_cursor() const;
Screen
& move(index r
, index c
);
Screen
& set(char);
Screen
& display(std
::ostream
&os
);
private:
std
::string contents
;
index cursor
;
index height
, width
;
};
#endif
screen.cpp 头文件具体实现文件
#include"screen.h"
#include<iostream>
#include<string>
using namespace std
;
Screen
::Screen(index hgth
, index wdth
, const string
&cntnts
= " "):
cursor(0), height(hgth
),width(wdth
)
{
contents
.assign(hgth
*wdth
, ' ');
if(!cntnts
.empty())
contents
.replace(0,cntnts
.size(),cntnts
);
}
char Screen
::get(index r
, index c
) const
{
if(!contents
.empty() && r
> 0 && c
> 0 && r
<= height
&& c
<= width
)
{
return contents
[(r
-1) * width
+ c
- 1];
}
else
{
cout
<< "超出屏幕范围!!!" << endl
;
}
return '!';
}
Screen
::index Screen
::get_cursor() const
{
return cursor
;
}
Screen
& Screen
::move(index r
, index c
)
{
index row
= r
* width
;
cursor
= row
+ c
;
return *this;
}
Screen
& Screen
::set(char c
)
{
contents
[cursor
] = c
;
return *this;
}
Screen
& Screen
::display(ostream
&os
)
{
string
::size_type index
= 0;
while(index
!= contents
.size())
{
os
<< contents
[index
];
if((index
+1)%width
== 0)
{
os
<< '\n';
}
++index
;
}
return *this;
}
main_screen.cpp 主函数
#include"screen.h"
#include<iostream>
using namespace std
;
int main()
{
Screen
myscreen(5,6,"aaaaa\naaaaa\naaaaa\naaaaa\naaaaa\n");
myscreen
.move(4,0).set('#').display(cout
);
cout
<< "光标当前所在位置和字符为: " << myscreen
.get_cursor()
<< " " << myscreen
.get() << endl
;
string
::size_type r
=1, c
=1;
cout
<< "输入你要获取的位置行列数字(从1开始):" << endl
;
cin
>> r
>> c
;
cout
<< myscreen
.get(r
,c
) << endl
;
return 0;
}
运行结果
转载请注明原文地址: https://www.6miu.com/read-5039527.html