数组下标运算符重载
函数声明形式
返回类型operator[](参数);
如果返回类型是引用,则数组运算符调用可以出现在等式的左边,接受赋值,即:
Obj[index] = value;
如果返回类型不是引用,则只能出现在等号的右边
Var = Obj[index];
#include <iostream> #include <string> using namespace std; char week_name[7][4] = { "mon","tu","wed","thu","fri","sat","sun" }; class WeekTemp { int temp[7]; public: int & operator[] (const char *name)//字符串作下标 { for (int i = 0; i < 7; i++) { if (strcmp(week_name[i], name) == 0) return temp[i]; } } }; //关于数组下标运算符重载的测试 int main() { WeekTemp beijing; beijing["mon"] = -3; beijing["tu"] = -1; cout << "Monday Temperature:" << beijing["mon"] << endl; return 0; }