Is it possible to overload = operator of type double?
I have the following:
double operator=(double a, Length b) {
return a = (b.getInches()/12+b.getFeet())*3.2808*0.9144;
}
It throws the following error:
'double operator=(double, Length)' must be a nonstatic member function
What am I doing wrong?
You cannot overload the assignment operator for a primitive type, but you can supply an operator that converts Length
to double
, giving you the desired effect:
class Length {
...
public:
operator double() {
return (getInches()/12+getFeet())*3.2808*0.9144;
}
};
main() {
Length len = ...;
...
double d = len;
}
Note that this conversion should be done only when the conversion is perfectly clear to the reader. For example, in this case you should make a get_yard
member function, like this:
class Length {
...
public:
double get_yards() {
return (getInches()+12*getFeet())/ 36.0;
}
};
Note that you do not need to convert feet to meters and then to yards - you can go straight from feet to yards; the conversion factor is 3.0
. You can also do the division last - see the modified expression above.
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