Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator[] overloading

Tags:

c++

There is a class like this:

class X {
    public:
        ...
    private:
        int changeable[3];
        int unchangeable[3];
};    

And this is its desirable usage:

X x;
x[0] = 1;  // here changeable[0] should be used
a = x[0];  // here unchangeable[0] should be used

Is there any way of defining operator[] in class X to implement that?

like image 886
01d Avatar asked Mar 03 '26 16:03

01d


2 Answers

I'd probably solve this with a proxy object:

class Xproxy
{
  int& changeable;
  int& unchangeable;

  Xproxy(int& c, int& u) : changeable(c), unchangeable(u)
  {}

  Xproxy& operator=(int i)
  {
    changeable=i
    return *this
  }

  operator int()
  {
    return unchangeable;
  }
};


class X
{
  int changeable[3];
  int unchangeable[3];

  Xproxy operator[](int i)
  {
     return Xproxy(changeable[i], unchangeable[i])
  }
};

So now when you call the operator[] on X, you get an Xproxy object that has references inside to both the changeable and unchangeable fields.

If you try to assign to Xproxy object it will invoke the operator= which assigns to the reference to the changeable. If you try to assign the Xproxy object to an int, it calls the cast operator which pulls from the unchangeable field.

like image 146
miked Avatar answered Mar 05 '26 05:03

miked


Sort of, but you need to be sneaky.

class X {
private:
  class XIndex;
public:
  XIndex operator[](int);
  //...
};

class X::XIndex {
public:
  operator int() const;
  void operator=(int val);
private:
  friend class X;
  XIndex(int* lvalue, int const* rvalue);

  int* _lval;
  int const* _rval;

  // Disallow copy and assignment.
  XIndex(const XIndex&);
  XIndex& operator=(const XIndex&);
};

X::XIndex X::operator[](int i) {
  // Check array bound?
  return XIndex(&changeable[i], &unchangeable[i]);
}

// Implementation of X::XIndex methods is an exercise.

Note that if the x[num] expression appears anywhere other than immediately left of an = operator, the "rvalue" is used. You can also add operator+=, operator*=, etc. if you want.

like image 41
aschepler Avatar answered Mar 05 '26 05:03

aschepler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!