Invalid operands of types class pointer and class pointer to binary operator+

时间:2017-04-10 01:45:17

标签: c++ class operator-overloading operators

I'm trying to overload the + operator so that it will take two classes. Inside each class, called Polynomial, is a Struct, named polyStruct, with data that i wish to add and then pass that sum back. But i am having no luck.

The full error is: error: invalid operands of types "Polynomial*" and "Polynomial*" to binary "operator+"

Here is my class:

class Polynomial {
public:
    Polynomial();
    Polynomial(ifstream *data);
    Polynomial* copyPolynomial();

    Polynomial* add(Polynomial *sec);
    Polynomial operator+(const Polynomial& sec);
    Polynomial* subtract(Polynomial *sec);
    //poly operator-(const poly&);

    bool equalPoly(Polynomial *sec);

    double evaluate(int x);

    int getDegree();
    void print();


private:
    struct poly {
        int exp;
        double coeff;
    } *polyStruct;

    List polyList;

};

Here is my operator overload:

Polynomial Polynomial::operator+(const Polynomial& sec) {
Polynomial temp = new Polynomial();

temp.polyStruct->exp = polyStruct->exp;
temp.polyStruct->coeff = polyStruct->coeff + sec.polyStruct->coeff;

return temp;
}

When attempting to use my operater i am doing the following: newPoly = main+sec; Where all the variables are individual initialized Polynomials. Any ideas on what im doing wrong?

2 个答案:

答案 0 :(得分:1)

From your error message it appears you are trying to use the operator on two pointers to Polynomials. If this is the case, you should dereference the pointers with * first.

class Polynomial {
public:
    Polynomial* operator+(const Polynomial& sec);
};

Polynomial* Polynomial::operator+(const Polynomial& sec) {
    Polynomial* temp = new Polynomial();

    temp->polyStruct->exp = polyStruct->exp;
    temp->polyStruct->coeff = polyStruct->coeff + sec.polyStruct->coeff;

    return temp;
}

Polynomial* polynomial1 = new Polynomial();
Polynomial* polynomial2 = new Polynomial();
Polynomial* polynomial3 = (*polynomial1) + (*polynomial2);

答案 1 :(得分:0)

Because you used the new operator when constructing temp inside the operator overload, the variable temp is not a Polynomial type, but a Polynomial* type.

Your operator overload, however, is declared to return a Polynomial type. You need to re-declare the operator overload to return Polynomial* instead, or dereference temp when you return it.

相关问题