Overloading operator= for double

耗尽温柔 提交于 2021-02-05 05:22:06

问题


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?


回答1:


You cannot overload operators for builtin (integral or floating point) types like double, and also you cannot globally overload the = operator for any type. The = operator can only be overloaded as a class member function.

See also: Can I define an operator overload that works with built-in / intrinsic / primitive types?




回答2:


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.



来源:https://stackoverflow.com/questions/23395932/overloading-operator-for-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!