M.sadraei M.sadraei -4 years ago 246
C++ Question

Square bracket [] operator overloading c++

I have a project that wants me to make a BigNum class in c++ (university project)
and it said to overload operator bracket for get and set
but the problem is if the set was invalid we should throw an exception the invalid is like

BigNum a;
a[i]=11;//it is invalid because its >9


in searching I found out how to make the set work

C++ : Overload bracket operators [] to get and set

but I didn't find out how to manage setting operation in c# you easily can manage the set value what is the equivalent of it in c++

to make it clear in C# we can say

public int this[int key]
{
set
{
if(value<0||value>9)throw new Exception();
SetValue(key,value);
}
}

Answer Source

You can define a wapper, say NumWapper, which wraps a reference of BigNum's element. The operator= of BigNum returns the wrapper by value.

a[i]=11;

is then something like NumWrapper x(...); x = 11. Now you can do those checks in the operator= of NumWrapper.


class BigNum {
 public:
  NumWrapper operator[](size_t index) {
    return NumWrapper(array_[index]);
  }

  const int &operator[](size_t index) const {
    return array_[index];
  }
};

In the NumWrapper, overload some operators, such as:

class NumWrapper {
 public:
  NumWrapper(int &x) : ref_(x) {}
  NumWrapper(const NumWrapper &other) : ref_(other.ref_) {}

  NumWrapper &operator=(const NumWrapper &other);
  int operator=(int x);
  operator int();

 private:
  int &ref_;
};

You can also declare the NumWrapper's copy constructor as private, and make BigNum his friend, for preventing user code from copying your wrapper. Such code auto x = a[i] will not compile if you do so, while user code can still copy it by auto x = static_cast<T>(a[i]) (kind of verbose though). Seems we are good.


These is also another approach: store the elements as a user defined class, say BigNumberElement. We now define the class BigNum as :

class BigNum {
 // some code
 private:
  BigNumberElement array_[10];
}

We need to declare a whole set operators for BigNumberElement, such as comparison(can also be done through conversion), assignment, constructor etc. for making it easy to use.

auto x = a[i] will now get a copy of BigNumberElement, which is fine for most cases. Only assigning to it will sometimes throw an exception and introduce some run-time overhead. But we can still write auto x = static_cast<T>(a[i]) (still verbose though...).

I prefer the first one. For as far as I can see, a compile-time error message is better than an unexpected exception thrown at run-time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download