inline 定义的函数必须放在 .h 文件中,否则编译器报错! 其次,注意写全称在 .h 里,如 std::
#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];} //定义成员函数 get() 返回位置处的字符
char get(index ht, index wd) const; //声明成员函数 get(a,b) get重载函数
index get_cursor() const; //声明成员函数 get_cursor() 返回index
Screen& move(index r, index c); //声明成员函数 move(a,b) 返回screen类引用
Screen& set(char); //声明成员函数 set(a) 返回screen类引用
Screen& display(std::ostream &os); //声明成员函数 display(输出流) 返回screen类引用
//----------------- 注意写 std:: ------------------------------------------------------
private:
std::string contents; //定义成员变量 内容字符串
index cursor; //定义成员变量 光标序号
index height, width; //定义成员变量 高,宽
};
#endif
#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)
{ //定义构造函数 光标位置为0,屏幕尺寸初始化
contents.assign(hgth*wdth, ' '); //填充文本初始化为hgth*wdth个 空格
if(!cntnts.empty())
contents.replace(0,cntnts.size(),cntnts); //从第0位开始,用输入的字符串替换掉
}
char Screen::get(index r, index c) const //定义成员函数 get(a,b)
{
if(!contents.empty() && r > 0 && c > 0 && r <= height && c <= width)
{
return contents[(r-1) * width + c - 1]; //返回(r,c)行列处的字符
}
else
{
cout << "超出屏幕范围!!!" << endl;
}
return '!';
}
Screen::index Screen::get_cursor() const //定义成员函数get_cursor()
{
return cursor; //注意返回值类型前加类名!
}
Screen& Screen::move(index r, index c) //定义成员函数 move(),光标cursor移动到指定位置
{
index row = r * width;
cursor = row + c;
return *this;
}
Screen& Screen::set(char c) //定义成员函数 set(a)
{
contents[cursor] = c; //光标处字符=c
return *this;
}
Screen& Screen::display(ostream &os) //定义成员函数 display()
{
string::size_type index = 0;
while(index != contents.size()) //把字符按每行宽度个输出
{
os << contents[index];
if((index+1)%width == 0)
{
os << '\n';
}
++index;
}
return *this;
}
#include"screen.h"
#include<iostream>
using namespace std;
int main()
{
Screen myscreen(5,6,"aaaaa\naaaaa\naaaaa\naaaaa\naaaaa\n");
//定义Screen类对象myscreen,初始化为5行6列的字符
myscreen.move(4,0).set('#').display(cout);
//move使光标移动到指定的第5行,第1列,返回的是对象自己*this
//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;
}