如何使类可分配给基元?
我想知道是否可以将我的
class Time
{
public:
Time();
explicit
Time(
const double& d);
Time&
operator=(
const Time& time);
Time&
operator=(
const double& d);
};
分配给原始双精度?
我经常使用 Time 作为 IV,并且需要对其进行大量标量操作,因此它需要与 DV 进行“混合”,DV 通常是普通的双精度数。添加第二个赋值运算符则起到了相反的效果。
尽管如此,许多操作仍然无法完成。我一直在 Time 类之外编写运算符,以允许在 Time 和 double 之间进行加法、减法、乘法和除法。但是由于不允许在类之外使用赋值运算符,因此我无法克服最后一个错误:
Error 1 error C2440: 'initializing' : cannot convert from 'double' to 'Time' linearfit.cpp 67
有人有这方面的经验吗?
谢谢!
I was wondering if it's possible to make my
class Time
{
public:
Time();
explicit
Time(
const double& d);
Time&
operator=(
const Time& time);
Time&
operator=(
const double& d);
};
assignable to the primitive double?
I'm using Time as an IV a lot and need to do a lot of scalar operations on it, so it needs to "mingle" with DV's which are usually ordinary doubles. Adding a second assignment operator did the trick the other way around.
A lot of operations still aren't possible with just this though. I've been writing operators outside of the Time class to allow for addition, substraction, multiplication and dividing between Time and double. But since assignment operators are not allowed outside a class, I'm unable to overcome this last error:
Error 1 error C2440: 'initializing' : cannot convert from 'double' to 'Time' linearfit.cpp 67
Has anybody got any experience with this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须编写/覆盖一个运算符。在本例中为强制转换运算符。
定义一个方法
You have to write/override an operator. In this case the cast-operator.
Define a method
您应该声明
operator double () const
以使Time
可转换为double
。无法重载原始类型的赋值运算符。
You should declare
operator double () const
to makeTime
convertible todouble
.There is no way to overload the assignment operator for primitive types.
您引用的错误很可能是由于将您的
Time(const double &d)
标记为explicit
引起的。删除从double
到Time
的显式转换和隐式转换应该可以工作(附带条件是,这也可能让它在您不希望发生的时候发生)。我可能还会按值传递 double 而不是 const 引用。从 Time 转换为 double 可以通过以下方式完成:
It appears likely that the error you've cited arises from having marked your
Time(const double &d)
asexplicit
. Remove the explicit, and implicit conversion fromdouble
toTime
should work (with the proviso that this may also let it happen at times you'd rather it didn't). I'd probably also pass the double by value rather than const reference.Converting from Time to double would be accomplished with: