How do I make a class assignable to primitives? Or

2019-02-25 06:11发布

I was wondering if it's possible to make my

class Time
{
    public:
        Time();

        explicit
        Time(
            const double& d);

        Time&
        operator=(
            const Time& time);

        Time&
        operator=(
            const double& d);
};

assignable to the primitive double?

I'm using Time as an IV a lot and need to do a lot of scalar operations on it, so it needs to "mingle" with DV's which are usually ordinary doubles. Adding a second assignment operator did the trick the other way around.

A lot of operations still aren't possible with just this though. I've been writing operators outside of the Time class to allow for addition, substraction, multiplication and dividing between Time and double. But since assignment operators are not allowed outside a class, I'm unable to overcome this last error:

Error   1   error C2440: 'initializing' : cannot convert from 'double' to 'Time'    linearfit.cpp   67

Has anybody got any experience with this?

Thanks!

3条回答
叼着烟拽天下
2楼-- · 2019-02-25 06:37

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;
};
查看更多
看我几分像从前
3楼-- · 2019-02-25 06:39

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; };
查看更多
Lonely孤独者°
4楼-- · 2019-02-25 06:41

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

查看更多
登录 后发表回答