Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator= for double

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?

like image 633
khajvah Avatar asked Dec 09 '22 08:12

khajvah


1 Answers

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.

like image 125
Sergey Kalinichenko Avatar answered Dec 22 '22 01:12

Sergey Kalinichenko