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

前端 未结 3 1819
庸人自扰
庸人自扰 2021-01-21 08:43

I was wondering if it\'s possible to make my

class Time
{
    public:
        Time();

        explicit
        Time(
            const double& d);

                


        
相关标签:
3条回答
  • 2021-01-21 09:11

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

    0 讨论(0)
  • 2021-01-21 09:26

    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;
    };
    
    0 讨论(0)
  • 2021-01-21 09:29

    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; };
    
    0 讨论(0)
提交回复
热议问题