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)
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 th开发者_运维问答ere a basic flaw in the approach to create the arrays? Thanks.
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
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 not a super efficient way, so if there is a better solution, please do share it. Thanks.
{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.
>>
精彩评论