Perl:构造对象数组
部分与这个问题相关,但不同,因为这是关于构造函数调用......
我想创建一个固定数量的数组的物体。
我可以这样做:
my @objects;
push( @objects, new MyPackage::MyObject() );
push( @objects, new MyPackage::MyObject() );
push( @objects, new MyPackage::MyObject() );
# ...
那是几种丑陋的方式。让它成为一个循环只会稍微好一些。
没有办法在 Perl 中创建(构造函数初始化的)对象数组吗?
事后思考的问题:
我想要创建的这些“对象”实际上是 SWIG 生成的 C 结构包装器,即没有“行为”的数据结构(除了 SWIG 生成的 get
和set
函数)。我只想将数组作为参数传递给 C 函数,该函数将为我填充结构;我是否需要调用构造函数,或者是否有一个快捷方式可以让 get
函数在之后读取结构内容? (是的,我对 OPerl 非常陌生......)
Partially related to this question but different, as this is about constructor calls...
I would like to create an array of a fixed number of objects.
I could do this:
my @objects;
push( @objects, new MyPackage::MyObject() );
push( @objects, new MyPackage::MyObject() );
push( @objects, new MyPackage::MyObject() );
# ...
That's several kinds of ugly. Making it a loop is only marginally better.
Isn't there a way to create an array of (constructor-initialized) objects in Perl?
Afterthought question:
These "objects" I want to create are actually SWIG-generated wrappers for C structs, i.e. data structures without "behaviour" (other than the SWIG-generated get
and set
functions). I just want to pass the array as a parameter to the C function, which will fill the structures for me; do I need to call constructors at all, or is there a shortcut to having the get
functions for reading the struct contents afterwards? (Yes, I am awfully new to OOPerl...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有不止一种简洁的方法可以做到这一点:
There Is More Than One Concise Way To Do It:
您可以通过向
push
提供多个参数来避免循环并重复相同的语句:这是可能的,因为
push
的原型是push ARRAY,LIST
。或者您可以使用数组编辑器以更直接的方式完成此操作(首选):
You can avoid the loop and repeating the same statement by supplying multiple arguments to
push
:This is possible because the prototype of
push
ispush ARRAY,LIST
.Or you can do it in a more straightforward way with an array composer (preferable):
你可以说
You can say
您可以构造一个对象列表并将其分配给您的数组:
You can construct a list of objects and assign it to your array: