如何在Eiffel中初始化对象数组? [英] How to initialise an array of objects in Eiffel?
问题描述
我正在尝试使用Eiffel实现生产者-消费者问题的解决方案.我有一个类PRODUCER的数组p和一个类CONSUMER的数组c声明并初始化如下:
I am trying to implement a solution to the Producer-Consumer problem using Eiffel. I have an array p of class PRODUCER and an array c of class CONSUMER declared and initialized as following:
local
p:attached ARRAY[PRODUCER]
c:attached ARRAY[CONSUMER]
do
!!p.make(1,5)
!!c.make(1,5)
但是,当我尝试访问数组组件之一中的功能(例如p.at(i).somefeature())时,它给出了运行时异常,提示对虚空目标进行功能调用".
But when I try to access a feature in one of the components of the array (like p.at(i).somefeature()), it gives a runtime exception saying "Feature call on void target".
关于如何解决此问题的任何想法?是因为我没有为数组的各个组件调用创建过程吗?还是创建数组的方法存在基本缺陷?谢谢.
Any ideas on how to solve this? Is it because I am not calling a creation procedure for individual components of the array? Or is there a basic flaw in the approach to create the arrays? Thanks.
我认为出现此问题是因为作为引用类型的数组的各个组件(在这种情况下,是生产者或消费者)被初始化为void.建议的解决方案是使用make_filled(default_value:T; low,high:INTEGER;),其中T是复杂类型.字符串数组的示例为 string_list:ARRAY [STRING] string_list.make_filled(",low,high) 导致将string_list的每个元素初始化为一个空格的字符串.关于如何为类PRODUCER赋予默认值的任何帮助吗?谢谢
I figured the problem occurs because the individual components of the arrays (in this case, a producer or a consumer), being a reference type is initialized to void. The solution suggested is to use make_filled(default_value:T;low,high:INTEGER;), where T is the complex type. An example is given for string arrays as string_list:ARRAY[STRING] string_list.make_filled(" ",low,high) causing each element of string_list to be initialized to a string that is a blank space. Any help on how to give a default value for the class PRODUCER? Thanks
我想我已经找到解决问题的办法.我只需要创建PRODUCER和CONSUMER的实例,并在make_filled的默认值中使用它们.然后我可以操纵p [i]和c [i].
I think I figured out the solution to the problem. I just had to create an instance of PRODUCER and CONSUMER and use those in the default value in make_filled. Then I can manipulate p[i] and c[i].
这不是一种超级有效的方法,因此,如果有更好的解决方案,请务必共享.谢谢.
This is nota super efficient way, so if there is a better solution, please do share it. Thanks.
推荐答案
{ARRAY}.make_filled
.如果元素不同,则可以将数组一一填充:
{ARRAY}.make_filled
is normally used when all the elements of the array should be the same. If the elements are different, the array can be filled one by one:
create p.make_empty
p.force (create {PRODUCER}.make ("producer 1"), 1) -- Use appropriate code to
p.force (create {PRODUCER}.make ("producer 2"), 2) -- create PRODUCER objects.
...
创建数组还有一种过时的语法,因此必须谨慎使用:
There is also a somewhat obsolete syntax to create arrays, so it has to be used with care:
p := <<
create {PRODUCER}.make ("producer 1"), -- Or some other code
create {PRODUCER}.make ("producer 2") -- to create producers.
>>
这篇关于如何在Eiffel中初始化对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!