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


    数组下标运算符重载

    函数声明形式

    返回类型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;
    }
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    软件测试工具
    Linux笔记
    Google Test
    字典dict()
    元组tuple 可迭代对象
    列表list
    一些总结
    format()
    列表list
    format() expandtabs() 输入表格数据
  • 原文地址:https://www.cnblogs.com/hujianglang/p/6629161.html
Copyright © 2020-2023  润新知