0

iv'e done operator overloading for +,*,=,[] for the class. they are all member functions. im trying to calculate this expression: p2 = (p1 + 2.5*p3 -0.9*p3)*p3; and it gives me the erorr: "no operator '='matches these operands. when im writing the operators as global functions it works. when im changing it to p2 = (p1 + p3 * 2.5 - p3 * 0.9)*p3; it works as member functions.

is there any way to make the original expression work with member functions?

here are all of the relevant functions:

double & Polynomial::operator[](int pos)const {
    return _polynom_arr[pos];
}

double & Polynomial::operator[](int pos) {
    return _polynom_arr[pos];
}

Polynomial & Polynomial::operator=(const Polynomial &polynom){
    for (int i = 0; i <= polynom._degree; i++) {
        _polynom_arr[i] = polynom._polynom_arr[i];
    }
    return *this;
}

Polynomial Polynomial::operator+(const Polynomial & polynom){
    int big, small, flag = 0;
    if (this->getDegree(true) > polynom.getDegree(true)) {
        big = this->getDegree(true);
        small = polynom.getDegree(true);
        flag = 1;
    }
    else {
        big = polynom.getDegree(true);
        small = this->getDegree(true);
    }
    Polynomial poly(big);
    for (int i = 0; i <= small; i++) {
        poly[i] = (*this)[i] + polynom[i];
    }
    if (flag) {
        for (int i = small + 1; i <= big; i++) {
            poly[i] = (*this)[i];
        }
    }
    else {
        for (int i = small + 1; i <= big; i++) {
            poly[i] = polynom[i];
        }
    }
    return poly;
}

Polynomial Polynomial::operator*(const Polynomial & polynom) {
    int deg1, deg2;
    deg1 = this->getDegree(true);
    deg2 = polynom.getDegree(true);
    Polynomial poly(deg1 + deg2);
    for (int i = 0; i <= deg1; i++) {
        for (int j = 0; j <= deg2; j++) {
            poly[i + j] += (*this)[i] * polynom[j];
        }
    }
    return poly;
}

Polynomial Polynomial::operator*(double num) {
    int deg = this->getDegree(true);
    Polynomial poly(deg);
    for (int i = 0; i <= deg; i++) {
        poly[i] = (*this)[i] * num;
    }
    return poly;
}
ore
  • 1
  • No, you can't. You need to provide both `operator+(Polynomial, int)` and `operator+(int, Polynomial)` to make the arguments interchangeable and the second cannot be done with member function. – Yksisarvinen May 04 '20 at 10:55
  • In the linked page, note the answer "The Decision between Member and Non-Member" recommends "If a binary operator treats both operands equally (it leaves them unchanged), implement this operator as a non-member function." Even if you weren't concerned with different types and just wanted `Polynomial + Polynomial`, a non-member is preferred because it allows implicit conversions on both operands, but a member allows only implicit conversions on the second operand, sometimes giving surprising differences between `x+y` and `y+x`... – aschepler May 04 '20 at 11:04

0 Answers0