【问题标题】:Overloading assignment operator for type deduction类型推导的重载赋值运算符
【发布时间】:2013-03-15 09:58:14
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你的意思是Seconds s = 2_h + 60_s;?或者更有可能:Seconds s = 2_h;?
  • 2_h.toSeconds() 无效。不过,您可以写 2_h .toSeconds() 使其有效。或者,做(2_h).toSeconds()

标签: c++ c++11 user-defined-literals


【解决方案1】:

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

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

并在 class Seconds:

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

【讨论】:

    【解决方案2】:

    正如答案中已经指出的那样,您需要实现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;
    }
    

    【讨论】:

    • 谢谢,但您犯了一个小错误。应该是lhs.value()+rhs.value()。
    猜你喜欢
    • 2011-05-02
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2016-01-04
    • 2017-10-07
    • 2012-04-26
    • 2016-02-16
    相关资源
    最近更新 更多