C++初级问题,谢谢~

来源:百度知道 编辑:UC知道 时间:2024/06/23 12:02:12
class Screen {
public:
typedef std::string::size_type index;
// return character at the cursor or at a given position
char get() const { return contents[cursor]; }
char get(index ht, index wd) const;
// remaining members
private:
std::string contents;
index cursor;
index height, width;
};

这个是我在C++primer中看到的代码,不明白以上代码中的第5行(char get() const { return contents[cursor]; })里的return contents[cursor]是什么意思,这个语法不太明白,请详细解释,谢谢~

char get() const { return contents[cursor]; }

char 定义 函数get()的返回类型。
const 表示返回值不能被修改

private:
std::string contents;
index cursor;
contents 为string 型变量(可视为一char型数组),cursor为一整型变量(按其名称意义知其将作为数组下标)

return contents[cursor];
这是把string当成一个数组,返回 char数组contents的第cursor个元素(计数从0开始),即返回一char型值

这是把string当成一个数组,返回contents的第cursor个元素(下标从0开始)

你不明白这句
你先看这个类里面的私有成员定义 std::string contents 首先声明了一个成员函数 有定义了一个 index cursor
那么你再看看这句 return contents[cursor]
是不是就有点思想了
以后看这些程序的时候 先去看他的定义
然后再看函数成员 等等 这样就不糊涂了

什么版本的C++
如果是VC。NET的话可能是索引指示器。