可以对string对象采用数组下标进行访问。
原因是数组访问操作符是C/C++的内置操作符(原意是数组访问和指针运算),所以标准库可以对数组访问操作符进行重载。
数组下表访问操作符重载:
1. 只能通过类的函数重载
2. 重载函数能且仅能使用一个参数(类型不同)
3. 通过不同的参数类型定义不同重载函数。
#include <iostream> #include <string> using namespace std; class Test { int a[5]; public: int& operator [] (int i) //函数下表符的重载 { return a[i]; } int length() { return 5; } }; int main() { Test t; for(int i=0; i<t.length(); i++) { t[i] = i; } for(int i=0; i<t.length(); i++) { cout << t[i] << endl; } return 0; }