将一种类型的向量分配给另一种类型的向量
我有一个“事件”课程。由于处理日期的方式,我们需要将此类包装在“UIEvent”类中,该类保存事件以及另一种格式的事件日期。
允许从事件到 UIEvent 来回转换的最佳方式是什么?我认为重载 UIEvent 的赋值或复制构造函数来接受事件(反之亦然)可能是最好的。
I have an "Event" class. Due to the way dates are handled, we need to wrap this class in a "UIEvent" class, which holds the Event, and the date of the Event in another format.
What is the best way of allowing conversion from Event to UIEvent and back? I thought overloading the assignment or copy constructor of UIEvent to accept Events (and vice versa)might be best.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我能想到两个简单的选择。
第一个选项是您描述的选项:创建一个采用另一种类型的对象的构造函数:
并使用 std::copy 将元素从一种类型的向量复制到另一种类型的向量:
第二个选择是编写一个非成员转换函数:
并使用 std::transform :
这样做的优点是类之间的直接耦合较少。另一方面,有时类无论如何都是自然耦合的,在这种情况下,第一个选项可能同样有意义并且可能不那么麻烦。
There are two simple options that I can think of.
The first option would be the one you describe: create a constructor that takes an object of the other type:
and use
std::copy
to copy elements from a vector of one type to a vector of the other:The second option would be to write a non-member conversion function:
and use
std::transform
:The advantage of doing it this way is that there is less direct coupling between the classes. On the other hand, sometimes classes are naturally coupled anyway, in which case the first option might make just as much sense and could be less cumbersome.
如果您可以将
Event
转换为UIEvent
(例如,如果UIEvent
有一个接受Event
的构造函数作为参数),那么以下将把一个向量分配给另一个向量:当然,如果转换有效,另一种方式也可以工作。
或者,您可以使用 std::copy() 来获得相同的效果。如果您无法在类接口内以一种方式进行转换,则编写一个进行转换的函数,然后使用 std::transform() :
当然,您可以添加任意多个在上面的函数对象中按照您的意愿重载
operator()()
,以便您可以使用相同的函数对象进行其他转换。If you can convert an
Event
to aUIEvent
(for example, ifUIEvent
has a constructor that takes anEvent
as parameter) then the following will assign one vector onto another:Naturally the other way around would work as well if that conversion works.
Alternatively you can use
std::copy()
to get the same effect. If you can't make the conversion in one way inside the class interface, then write a function that makes the conversion and then usestd::transform()
:You can, of course, add as many overloads as you wish of
operator()()
in the above function object so you can use that same function object for other conversions.