类型演绎的重载赋值操作符

Overloading assignment operator for type deduction

本文关键字:赋值操作符 重载 演绎 类型      更新时间:2023-10-16

ideone代码:http://ideone.com/Qp8Eqg

我的问题是,是否有可能仅基于左值强制转换?例如

[Seconds] s = 2_h + 60_s;
cout <<s.getSeconds()<<endl;

显然,我必须写2_h.toSeconds()之类的东西,但这太啰嗦了,没有达到目的。

允许这样做(这更像是你的问题而不是你写的,如果我错了请纠正我):

Seconds s = 2_h;
operator Seconds() const添加到Hours类:
class Hours {
    unsigned long long _hours;
public:
    Hours(unsigned long long hours) : _hours(hours) { }
    operator Seconds() const;
    unsigned long long getHours() const {
        return this->_hours;
    }
};

并在类Seconds:

之后定义
Hours::operator Seconds() const { return this->_hours * 3600; }

正如在给出的答案中已经指出的,您需要实现operator Seconds ()以允许从HoursSeconds的自动转换。有了这个操作符,您还可以简化operator+。为了改善运行时,你还可以引入一些constexpr来在编译时对值进行评估。

#include <iostream>
class Seconds {
    public:
        constexpr Seconds(const Seconds& other) : seconds_(other.seconds_) {}
        constexpr Seconds(unsigned long long seconds) : seconds_(seconds) {}
        Seconds& operator=(const Seconds& other) {
            seconds_  = other.seconds_;
            return *this;
        }
        constexpr unsigned long long value() const {
            return this->seconds_;
        }
    private:
        unsigned long long seconds_;
};

class Hours {
    public:
        constexpr Hours(const Hours& other) : hours_(other.hours_) {}
        constexpr Hours(unsigned long long hours) : hours_(hours) {}
        Hours& operator=(const Hours& other) {
            hours_ = other.hours_;
            return *this;
        }
        unsigned long long value() const {
            return this->hours_;
        }
        operator Seconds () const { return Seconds(hours_*60*60); }
    private:
        unsigned long long hours_;
};

constexpr Seconds operator+(const Seconds& lhs, const Seconds& rhs) 
{
    return Seconds(lhs.value()+rhs.value());
}
constexpr Hours operator "" _h(unsigned long long hours) {
    return Hours(hours);
}
constexpr Seconds operator "" _s(unsigned long long seconds) {
    return Seconds(seconds);
}

int main() {
    using namespace std;
    Seconds s = 1_h + 10_s;
    cout <<s.value()<<endl;
    s = 2_h + 60_s;
    cout <<s.value()<<endl;
    return 0;
}