Aug 8, 2013 at 5:03pm UTC
im writing my own version of Bajarne Stroustrop's calculator, and i want to add % to the operators it can use. my only issue is doubles can't use modulo. i thought this would be no issue; i could just overload the operator. so i wrote this:
1 2 3 4 5 6 7 8 9 10 11
double operator %(double LValue, double RValue)
{
int CLValue, CRValue;
CLValue = LValue;
CRValue = RValue;
CLValue %= CRValue;
return (double ) (CLValue);
}
but got this:
test.cpp:95:47: error: ‘double& operator%(double, double)’ must have an argument of class or enumerated type
short of writing a class to emulate double, is there a quick and easy hack around this?
Last edited on Aug 8, 2013 at 5:16pm UTC
Aug 8, 2013 at 5:10pm UTC
Even if the C++ would allow to overload operators for fundamental types your code is invalid because the operator calls itself recursively
1 2 3 4 5 6 7 8 9
double & operator %(double LValue, double RValue)
{
int CLValue, CRValue;
CLValue = LValue;
CRValue = RValue;
return (double ) (CLValue % CRValue ); // here it calls itself recursively
}
Moreover you are trying to return a reference to a local temporary expression.
Last edited on Aug 8, 2013 at 5:13pm UTC
Aug 8, 2013 at 5:12pm UTC
1) i didnt mean to have the & there. thanks for pointing it out.
2) sorry my mistake. ill make it so it doesnt call it recursively.
Aug 8, 2013 at 5:15pm UTC
Oh, I am wrong. It does not call itself recursively. You are calling operator % for integers.
By the way C# applies operator % for doubles. For example 3.2 % 2 will be equal to 1.2.
Aug 8, 2013 at 5:16pm UTC
good to know. and wait it doesnt? i thought that () had higher precedence than &, causing it to do the conversion first.
Aug 8, 2013 at 5:26pm UTC
The casting was applied to int expression (CLValue % CRValue). So it has nothing with the operator % for doubles.
Aug 8, 2013 at 5:27pm UTC
ah ok thanks. but anyways, is there a way to do this without writing a class?
Aug 9, 2013 at 2:29am UTC
naraku9333 + 1
Thank you.