Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Unary - Operator Overload Won't Compile

I am attempting to create an overloaded unary - operator but can't get the code to compile. A cut-down version of the code is as follows:-

class frag
{
    public:

        frag myfunc  (frag oper1,
                      frag oper2);
        frag myfunc2  (frag oper1,
                      frag oper2);

        friend frag operator + (frag &oper1,
                                frag &oper2);

        frag operator - ()
        {
            frag f;
            f.element = -element;
            return f;
        }

    private:

        int element;

};

frag myfunc (frag oper1, frag oper2)
{
    return oper1 + -oper2;
}

frag myfunc2 (frag oper1, frag oper2)
{
    return oper1 + oper2;
}

frag operator+ (frag &oper1, frag &oper2)
{
    frag innerfrag;
    innerfrag.element = oper1.element + oper2.element;
    return innerfrag;
}

The compiler reports...

/home/brian/Desktop/frag.hpp: In function ‘frag myfunc(frag, frag)’:
/home/brian/Desktop/frag.hpp:41: error: no match for ‘operator+’ in ‘oper1 + oper2.frag::operator-()’
/home/brian/Desktop/frag.hpp:16: note: candidates are: frag operator+(frag&, frag&)

Could anyone suggest what I need to be doing here?

like image 574
Brian Hooper Avatar asked Dec 22 '22 03:12

Brian Hooper


2 Answers

const-correctness

This has to be

 frag operator+ (const frag &oper1, const frag &oper2);

or else the operands can't be temporaries, such as the return value of operator-

And unary minus should rather be:

frag operator - () const;

since it shouldn't modify the operand.

like image 88
UncleBens Avatar answered Jan 05 '23 07:01

UncleBens


You don't have an operator+ that can operate on temporaries. Temporaries cannot be passed as non-const reference.

Change the signature of your operator+ to:

frag operator + (const frag &oper1, const frag &oper2);
like image 21
JoeG Avatar answered Jan 05 '23 07:01

JoeG