0

i have a certain class and i want to create 2 operators that will work together

like class with array and i want to change a certain index in the array

like this obj[3]=5

is this possible? if yes,how?

this is the code i made for [] operator


double Polynomial::operator[](int index) const {
    int maxT = this->currentMax;
    if (index > 0 && index < this->getDegree(false))
        return this->coefficients[index];
    cout << "overflow in index";
    system("pause");
}

Tal K
  • 53
  • 1
  • 6
  • 1
    Does this answer your question? [overloading assignment operator With subscript operator](https://stackoverflow.com/questions/20168543/overloading-assignment-operator-with-subscript-operator) – scohe001 Apr 22 '20 at 19:50
  • TL;DR: `double Polynomial::operator...` --> `double &Polynomial::operator...` – scohe001 Apr 22 '20 at 19:50
  • While it's not _wrong_ to do bounds checking in `operator[]` it's unconventional. Most containers skip bounds checking in `operator[]` (to be as fast as possible) and provide a member function called `at()` which does bounds checking and throws an exception if `index` is out of bounds. Btw, `index` should usually be an `unsigned` type, like `size_t`. Here's a simple example to play with: https://godbolt.org/z/qr26cd – Ted Lyngmo Apr 22 '20 at 20:07
  • There is no **single** operator `[]=`, so you can't overload it. You can overload the `[]` operator and the `=` operator. – Thomas Matthews Apr 22 '20 at 20:16
  • @ThomasMatthews I don't see operator `[]=` mentioned or implied. The title mentions `[]` and `=` separately. – Ted Lyngmo Apr 22 '20 at 20:20
  • @TedLyngmo When I read the title, it didn't mention using `[]` and `=` separately. – Thomas Matthews Apr 22 '20 at 20:23
  • @ThomasMatthews Maybe I have my forgiving glasses on :-) "_[] operator and = operator_" sounds like "_`operator[]` and `operator=`_" to me and the implementation of `operator[]` (not `operator[]=`) also makes me think that OP knows that they are separate operators. – Ted Lyngmo Apr 22 '20 at 20:26

1 Answers1

0

Your operator[] is a const method, hence it cannot be used to modify members. Unless you want to do something fancy on assigning to an element, you don't really need some operator= when your operator[] returns a reference to the element.

As mentioned in comments, doing bounds-checking in operator[] is not typical. Consider that in a loop each call to operator[] would do bounds-checking even if the user made sure that only valid indices are used. Thats not quite efficient. So in addition to your const operator you can provide this one

double& Polynomial::operator[](size_t index)  {  // <-- no const
    return coefficients[index];
}

Assuming you also have a size method you can then write a loop:

for (size_t i=0; i< poly.size(); ++i) {
    poly[i] = i;
}

PS: system("pause") is a no-go, see system("pause"); - Why is it wrong?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185