overloading assignment operator With subscript operator

后端 未结 5 447
忘了有多久
忘了有多久 2020-12-19 16:31

I overloaded both subscript operator and assignment operator and I am trying to get right value to assignment operator example Array x; x[0]=5; by overloading

5条回答
  •  误落风尘
    2020-12-19 17:19

    The assignment operator you wrote would apply to an array, not an array element. For example

    x = 5;
    

    would use your assignment operator. From the looks of it you want to have an overloaed assignment operator applied when using the subscript operator. The only way to get something like this to work is using a proxy class:

    struct Proxy {
        Proxy(Array* array, int* element);
        void operator= (int rhs) {
            array->two = rhs;
            *element = rhs;
        }
        operator int() const { return *element; }
    };
    Proxy operator[](int index)
    {
        one=index;
        return Proxy(this, ptr + index);
    }
    

提交回复
热议问题