将一个类的对象转换为另一个类的对象
问题描述
除了存储在其中的数据类型外,我有两个几乎相等的类.一个类包含所有双精度值,而另一个包含所有浮点值.
I have two classes which have are nearly equal except the data types stored in them. One class contains all double values while other contains all float values.
现在我有一个 DoubleClass 点,我想将其转换为 FloatClass.
Now I have a point of DoubleClass which I want to convert to FloatClass.
一种简单的方法是创建一个方法来创建一个新的 FloatClass 对象,填充所有值并返回它.有没有其他有效的方法来做到这一点.
One simple way is to make a method which creates a new FloatClass object, fills all values and return it. Is there any other efficient way to do this.
推荐答案
使用转换运算符:
然后就用它吧:
编辑
我将运算符更改为 explicit
而不是 implicit
因为我在示例中使用了 FloatClass
强制转换.我更喜欢使用 explicit
而不是 implicit
所以它迫使我确认对象将被转换为 的类型(对我来说这意味着更少的干扰错误 + 可读性).
I changed the operator to explicit
instead of implicit
since I was using a FloatClass
cast in the example. I prefer to use explicit
over implicit
so it forces me to confirm what type the object will be converted to (to me it means less distraction errors + readability).
但是,您可以使用 implicit
转换,然后您只需要这样做:
However, you can use implicit
conversion and then you would just need to do:
参考
这篇关于将一个类的对象转换为另一个类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!