本文介绍了重载类型扣除的赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是ideone程式码:
我的问题是,是否可以强制基于左值单独的转换?例如,
[秒] s = 2_h + 60_s;
cout<< s.getSeconds()<< endl;
显然,我必须写一些类似2_h.toSeconds
解决方案
要允许这样做(这比你写的更可能是你的问题,如果我错了):
秒s = 2_h;
以下操作将会起作用:Add operator Seconds()const
到类小时
:
b unsigned long long_hours;
public:
小时(unsigned long long hours):_hours(hours){}
操作符Seconds()const;
无符号长整型getHours()const {
return this-> _hours;
}
}; class Seconds 之后定义 code>: Hours :: operator Seconds()const {return this-> _hours * 3600; }
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.
解决方案 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; }
这篇关于重载类型扣除的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!