Overloading assignment operator for type deduction

為{幸葍}努か 提交于 2019-12-24 14:08:37

问题


Here's the ideone code: http://ideone.com/Qp8Eqg

My question is, is it possible to force a conversion based on the lvalue alone? For example,

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

Obviously, I would have to write something like 2_h.toSeconds(), but that would be too verbose and doesn't achieve the idea.


回答1:


To allow this (which is more likely your question than what you wrote, correct me if I'm wrong):

Seconds s = 2_h;

the following would work: Add operator Seconds() const to class 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;
    }
};

and define it after class Seconds:

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



回答2:


As already noted in the answer given you need to have the operator Seconds () implemented to allow automatic conversion from Hours to Seconds. With this operator in place you can also simplify operator+. And to improve run-time you can also throw in some constexpr to have values evaluated at compile time.

#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;
}


来源:https://stackoverflow.com/questions/15622958/overloading-assignment-operator-for-type-deduction

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