0

I need to overload operator[] in c++, but with checking what r-value is.

class polynomial
{
    int n; //polynomial degree
    double *a; //array of polynomial value
    {...}
    polynomial::polynomial (initializer_list<double> p)
    {
        n = p.size()-1;
        a = new double[n+1];
        copy(p.begin(), p.end(), a);
    }
    double& polynomial::operator [] (const int i)
    {
        return a[n-i];
    }
}

main()
{
    polynomial p = {1,2,3};
    p[0]=0;
}

And i want throw exception if there is =0 after p[] with index 0.

Ozi
  • 1
  • 1
  • 1
    You can't throw an exception from `operator[]` for something that happens in `operator=`. So you'll have to overload `operator=`. But you can't overload `operator=` for `double`, so you'll have to return something other than `double` from `operator[]`. Something like a proxy object: http://stackoverflow.com/questions/994488/what-is-proxy-class-in-c – Benjamin Lindley Apr 10 '16 at 21:04
  • So what return in `operator[]` to overload `operator=` and throw exception in `operator=` – Ozi Apr 10 '16 at 21:07
  • I edited my comment with a link. As a matter of fact, I think that answers your question, making it a duplicate. I'll mark it as such. – Benjamin Lindley Apr 10 '16 at 21:09
  • You need a proxy for that (And get get used to zero based indices) –  Apr 10 '16 at 21:10
  • @DieterLücking: I don't think he's trying to not use zero based indices. I think he's trying to prevent the leading coefficient of the polynomial from being 0. Though I'm not sure why. – Benjamin Lindley Apr 10 '16 at 21:23
  • Thanks with proxy that work. I need to throw exception if someone try change value on the highest degree to 0 because it change degree of polynomial and Profesor order to protect program from that. Now everything work properly, thanks a lot. – Ozi Apr 10 '16 at 22:06

0 Answers0