C++程序设计方法3:数组下标运算符重载

时间:2022-09-03 19:26:13

数组下标运算符重载

函数声明形式

返回类型operator[](参数);

如果返回类型是引用,则数组运算符调用可以出现在等式的左边,接受赋值,即:

Obj[index] = value;

如果返回类型不是引用,则只能出现在等号的右边

Var = Obj[index];

#include <iostream>
#include <string> using namespace std; char week_name[][] = { "mon","tu","wed","thu","fri","sat","sun" };
class WeekTemp
{
int temp[];
public:
int & operator[] (const char *name)//字符串作下标
{
for (int i = ; i < ; i++)
{
if (strcmp(week_name[i], name) == )
return temp[i];
}
}
}; //关于数组下标运算符重载的测试
int main()
{
WeekTemp beijing;
beijing["mon"] = -;
beijing["tu"] = -;
cout << "Monday Temperature:" << beijing["mon"] << endl;
return ;
}