[]用于访问一组元素中的一个元素。默认的,数组是支持下标访问的。
[]中的下标称为:索引,key,唯一标志符
当一个对象设计用于包含多个元素时,可以重载操作符[]
比如一个字符串Text包含多个元素(每个元素是一个字符串)
Text txt(“helloworld”);
char ch = text[0];
比如在一个DataStore里面存储多个Student的记录。
DataStore ds;
Student& st = ds[“xiaoming”];
重载操作符的一般形式
Element& opeartor
{
}
(1)opeartor[]是不变得
(2)返回值:一般应该返回一个子元素的引用,这样可以作为一个左值,可读可写。
(3)参数:类型可以自己选择,用于指定元素的下标。
示例一 :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
class Text{
public:
Text(const char* str)
{
m_size = strlen(str)+1;
m_buf = new char[m_size];
strcpy(m_buf,str);
}
~Text()
{
delete [] m_buf;
}
char& operator[](int index)
{
return m_buf[index];
}
public:
int m_size;
char* m_buf;
};
int main()
{
Text t1("heloworld");
char ch = t1[0];
t1[0] = 'H';
return 0;
<