3

I tried do like this but got an error in constructor.

E2029 'OF' expected but '[' found

Dish = class
 public
    Dish_name: string;        
    Dish_id: integer;         
    Dish_number: integer;     
    Dish_units: string;        
    Dish_price: integer;      
    Dish_prime_cost: integer; 
    Dish_ingredients_id: array[1..100] of  Ingredients;

constructor Create( NewDish_name: string;
    NewDish_id: integer;  NewDish_number: integer;
    NewDish_units: string;  NewDish_price: integer;
    NewDish_prime_cost: integer;
    NewDish_ingredients_id:array[1..100] of  Ingredients);

  destructor Destroy;
end;

Ingredients it is class.

2 Answers 2

5

You cannot declare a static array inline as a parameter. You need to declare a type:

type
  TIngredientsArray = array[1..100] of Ingredients;

And then use that type for both your field and your argument.

However, a statically sized array is probably not the best choice. What if you need more than 100 ingredients? What if you need only 1, but are forced to pass around 100? As your code stands, how can the dish class know how many ingredients have actually been provided?

Consider using a dynamic array instead.

You should also think about the lifetime and ownership of these ingredient objects. You pass the objects to the dish class. Does it assume ownership? That is, who is responsible for destroying all the ingredient objects? If you could use a value type for the ingredients, that is a record, then you might find that makes lifetime management simpler.

It is also idiomatic to use zero-based indexing for arrays in Delphi. Dynamic arrays are zero-based. Standard collection classes are zero-based. If you start using one-based arrays then experience says that you are going to store up confusion in the future.

Sign up to request clarification or add additional context in comments.

2 Comments

TObjectlist<T> would be more suitable, no?
@whosrdaddy Maybe yes, maybe no
0

You can try this:

Dish_ingredients_id: TArray<Ingredients>;
   destructor Destroy; override;
   public 
   procedure AddId(ingredient:Ingredients); 

   procedure AddId(ingredient:Ingredients);

   var x:integer;
   begin
   x:= Length(Dish_ingredients_id) +1;
   SetLength(Dish_ingredients_id,x);

   Dish_ingredients_id[x-1] := ingredient;
   end;

   destructor Destroy;
   var i:integer;
   begin
   for i := 0 to Length(Dish_ingredients_id)-1 do begin
   if Dish_ingredients_id[i] <> nil then
   Dish_ingredients_id[i].Free;
   end;
   inherited;
   end;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.