相关知识:
- 下标操作符
[]
通常用于访问数组元素。 - 下标操作符
[ ]
常用于在容器类型中以下标方式获取元素; - 下标运算符重载函数只能定义成员函数;
- 在
C++
中,在重载下标运算符 “[ ]
” 时,认为它是一个双目运算符,假设X
是某一个类的对象,类中定义了重载“[ ]
”的operator[ ]
函数,则表达式:X[Y]
;可被解释为:X.operator[](Y)
;代码相关内容:
- 下标操作符:
[]
- 两个版本:可变成员函数;常量成员函数;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using namespace std;
class String
{
public:
String(char const *chars = "");
char &operator[](std::size_t index) throw(String);
char &operator[](std::size_t index) const throw(String);
void print();
private:
char *ptrChars; // 有一个私有成员是字符指针;
static String errorMessage;
};
void String::print()
{
cout << ptrChars << endl;
}
// 定义越界异常信息;
String String::errorMessage("Subscript out of range.");
// 定义可变成员函数;
char &String::operator[](std::size_t index) throw(String)
{
cout << "nonconst" << endl;
// 首先检查索引是否越界,如果越界抛出异常信息;
if (index >= std::strlen(ptrChars))
throw errorMessage;
return ptrChars[index];
}
// 定义常量成员函数;
char &String::operator[](std::size_t index) const throw(String)
{
cout << "const" << endl;
// 首先检查索引是否越界,如果越界抛出异常信息;
if (index >= std::strlen(ptrChars))
throw errorMessage;
return ptrChars[index];
}
String::String(char const *chars)
{
// 如果是空指针就变成空字符串;
chars = chars ? chars : "";
ptrChars = new char[std::strlen(chars) + 1];
std::strcpy(ptrChars, chars);
}
int main()
{
String s("Hello");
s.print();
cout << s[0] << endl;
s[0] = 'A';
s.print();
String const s2("HTL2018");
cout << s2[2] << endl;
return 0;
}代码执行结果:
参考链接:
C++ 重载下标运算符 [ ]