1

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

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

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

显然,我必须编写类似 2_h.toSeconds() 的东西,但这太冗长并且无法实现这个想法。

4

2 回答 2

3

为了允许这样做(这比你写的更可能是你的问题,如果我错了,请纠正我):

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; }
于 2013-03-25T19:37:11.857 回答
1

正如给出的答案中已经指出的那样,您需要operator Seconds ()实施以允许从Hours到的自动转换Seconds。有了这个运算符,您还可以简化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;
}
于 2013-03-25T19:53:24.420 回答