重载[] int& operator[ ]( )

https://blog.csdn.net/qq_29344757/article/details/76855218

格式:

返回类型& operator[] (输入参数列表);

注意返回的是引用;

重载操作符的原则是不能改变操作符的原有语义和操作数的个数;

”[]”用于取元素的值,且只有一个操作数,为括号内的值,这个是不可被改变的,但是括号内的值是针对该数组而操作的,所以”[]”操作符肯定有一个数组对象,这也就决定了对”[]”的重载实现的函数只能是类的成员函数,因为类的成员函数具有this指针,它可以指向对象本身(对象可以内含一个数组嘛):类必须得有一个数组成员?

因为返回的是引用,所以必然对象内部已经有存在的数组列表,链表也行,可以引用就行!

class cls
{
private:
    int ar[6];
public:
    cls();
    int& operator[] (int i);    //重载"[]"操作符
};
cls::cls()
{
    int i;
    for (i = 0; i < 6; i++)
    {
        ar[i] = i + 1;
    }
}
int& cls::operator[] (int i)    //返回引用,这样才可以对返回值赋值
{
    return ar[i];
}

int main(void)
{
    cls c;
    printf("c[1] = %d\n", c[1]);
    c[4] = 16;
    printf("c[4] = %d\n", c[4]);
    return 0;
}

”[]”内的操作数支持字符串类型;

class cls
{
    private: int ar[6]; 
public:
    int& operator[] (int i);            //重载"[]"操作符,"[]"内的操作数的操作数是int类型
    int& operator[] (const char* str);  //重载"[]"操作符,"[]"内的操作数是字符串类型
};
int& cls::operator[] (const char* str)
{
    //1st 2nd 3rd 4th 5th
    if (!strcmp("1st", str))
        return ar[0];

    if (!strcmp("2nd", str))
        return ar[1];
}
int main(void)
{
    cls c;
    printf("c[\"5th\"] = %d\n", c["1th"]);
    c["2nd"] = 66;
    printf("c[\"2nd\"] = %d\n", c["2nd"]);
    return 0;
}

 

posted @ 2018-12-16 21:24  kuaqi  阅读(2039)  评论(0编辑  收藏  举报