Vinay Lohana
Vinay Lohana

Reputation: 13

Overloading operator [ ] to use as a setter for Polynomial class

I have created a Polynomial class but I want to overload indexing operator to be used as a setter, for example, myPolyObject[0] = 2.5 but It's giving me an error when trying to overload it.

class Polynomial
{
public:
    Polynomial();
    Polynomial(Polynomial&);
    Polynomial(double* coefficient, int size);
    ~Polynomial() { delete [] polynomial ; }
    double operator [] (int exponent) const;
    friend ostream& operator << ( ostream& , const Polynomial&);
    Polynomial& operator = (const Polynomial&);
    double evaluate(double x) const;
    int getSize() const;
    double operator [] (int exponent, double coefficient);
    Polynomial& operator + ( Polynomial& );
    Polynomial& operator + ( double x );
    Polynomial& operator - (Polynomial&);
    Polynomial& operator - (double x);
    Polynomial& operator * (Polynomial&);
    Polynomial& operator * (double x);
private:
    double* polynomial;
};

In this code, I want double operator [] (int exponent, double coefficient) to take an index (exponent) for the array and set the value at that index to the double coefficient value.

Upvotes: 0

Views: 261

Answers (1)

rmawatson
rmawatson

Reputation: 1943

Your question seems to want two different things, the first bit is answered in the comments, return a reference. Here is an example for completeness,

struct example
{
    double value_[10];
    double& operator [] (int index) {
       return value_[index];
    }
};

int main() {
    example e;
    e[0] = 2.2;
    std::cout << e.value_[0] << std::endl;
}

Demo

You then say..

I want double operator [] (int exponent, double coefficient) to take an index (exponent) for the array and set the value at that index to the double coefficient value.

You can't have operator[] with multiple arguments. A couple of options are; accept a std::pair<int,double>, which has pretty clean syntax. for example..

struct example
{
    double operator [] (const std::pair<int,double>& values) {
        return 2.0;
    }
};

int main() {
    example e;
    e[{1,2.2}];
    //or 
    e[std::make_pair(1,2.2)];
}

Demo

Or if you really want the comma, you could make your own type for the exponent and overload the comma operator.

struct exponent
{
    int exp_;
    double coeff_;
    exponent(int value) : exp_(value),coeff_(0){}

    operator std::pair<int,double>() {
        return std::make_pair(exp_,coeff_);
    }

    exponent& operator,(double coeff) {
        coeff_ = coeff;
        return *this;
    }
};

struct example
{
    double operator [] (const std::pair<int,double>& values) {
        return 2.0;
    }
};

int main() {
    example e;
    e[exponent(1), 3.3];
}

Demo

I'd personally go with something like the first option, or overload operator() instead.

Upvotes: 2

Related Questions