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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With