类型演绎的重载赋值操作符
Overloading assignment operator for type deduction
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 ()
以允许从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;
}
相关文章:
- c++中的重载赋值操作符
- 复制构造函数,赋值操作符重载
- c++复制构造函数,重载赋值操作符,方法get()
- 赋值操作符重载
- 当类是子类时重载赋值操作符
- 模板类的重载赋值操作符
- 使用重载赋值操作符
- 类和向量的重载赋值操作符
- c++模板赋值操作符重载——赋基本类型给对象
- 在可强制转换为另一个模板类型的类模板中重载赋值操作符
- 无法重载赋值操作符
- 赋值操作符重载:错误处理场景
- 使用重载复合赋值操作符时的运行时错误
- 赋值操作符重载未被调用
- c++ const重载赋值操作符机制
- 在子类类中重载基类赋值操作符会导致二义性赋值错误
- 创建了自己的字符串类——重载赋值操作符和析构函数的错误
- 子类,赋值操作符重载
- 算术和赋值操作符重载-返回值,范围,组合表达式
- 模板赋值操作符重载之谜