I need to overload the operator =, to preform the following arithmetic operation
ID: 3927673 • Letter: I
Question
I need to overload the operator =, to preform the following arithmetic operation.
num = R2;
R2 = num;
num is a float, while R2 is a fraction with a whole, numer, and denom.
R3 = num, works and this is the code that I have for it.
frapri & frapri :: operator = (const float x) { //R3 = num;
frapri result;
result.whole = x;
result.numer = 0;
result.denom = 0;
return result;
}
I tried doing something similar for R2 = num;
float & frapri :: operator = (const frapri &x) {
float result;
numer = (x.denom *x.whole + x.numer);
denom = x.denom;
result = numer/denom;
return result;
}
but it doesn't work, it gives me an error saying
"no suitable conversion function from "frapri" to "int" exists.
I am not sure what I am doing wrong, could someone explain?
This is in c++.
Explanation / Answer
Here is the modified code for you:
float & frapri :: operator = (const frapri &x) {
float result; //Declares a float variable result.
numer = (x.denom *x.whole + x.numer); //Assigns the value to numer.
denom = x.denom; //Assigns the value to denom.
result = (float)numer/denom; //Assigns the fraction value to result.
return result;
}
If this doesn't work, just send your whole code atleast the class frapri, so that I can develop it for you.