How do I make a class assignable to primitives? Or, how do I make a scalar class?

≡放荡痞女 提交于 2019-12-01 22:30:43

You have to write/override an operator. In this case the cast-operator. Define a method

operator double() { return double_however_computed_from_your_time; };

It appears likely that the error you've cited arises from having marked your Time(const double &d) as explicit. Remove the explicit, and implicit conversion from double to Time should work (with the proviso that this may also let it happen at times you'd rather it didn't). I'd probably also pass the double by value rather than const reference.

Converting from Time to double would be accomplished with:

class Time { 
// ...
     operator double() const;
};

You should declare operator double () const to make Time convertible to double. There is no way to overload the assignment operator for primitive types.

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