gpt4 book ai didi

艾达:如何解决 "Circular Unit Dependency"?

转载 作者:行者123 更新时间:2023-12-04 14:15:14 26 4
gpt4 key购买 nike

假设我有两个记录:Person 和 Animal。每条记录都在一个单独的包中。

包人:

with animals;
use animals;

package persons is

type person is record
...
animalref: animalPOINTER;
...
end record;

type personPOINTER is access person;

end persons;

包装动物:
with persons;
use persons;

package animals is
type animal is record
...
ownerref: personPOINTER;
...
end record;

type animalPOINTER is access animal;

end animals;

我这里有循环单元依赖性,编译器产生 fatal error 。

有没有人有解决此类问题的模式?

谢谢!

最佳答案

您需要 limited with ,它的引入正是为了解决这个问题。见 Rationale for Ada 2005, section 4.2 .
AnimalsPersons是对称的(我的编辑器已经调整了布局和大小写;我为每个组件添加了一个记录组件,因此下面的演示程序可以打印一些内容):

limited with Animals;
package Persons is

-- One of the few things you can do with an incomplete type, which
-- is what Animals.Animal is in the limited view of Animals, is to
-- declare an access to it.
type AnimalPOINTER is access Animals.Animal;

type Person is record
Name : Character;
Animalref : AnimalPOINTER;
end record;

end Persons;

limited with Persons;
package Animals is

type PersonPOINTER is access Persons.Person;

type Animal is record
Name : Character;
Ownerref : PersonPOINTER;
end record;

end Animals;

演示程序完整查看 AnimalsPersons .这个例子很笨拙;您可以通过将子程序添加到 Animals 来更好地组织事情。和 Persons .注意 Animals的正文可以(并且必须) with Persons;如果它需要在 Persons 中使用任何东西.
with Ada.Text_IO; use Ada.Text_IO;
with Animals;
with Persons;
procedure Animals_And_Persons is
A : Persons.animalPOINTER := new Animals.Animal;
P : Animals.PersonPOINTER := new Persons.Person;
begin
A.all := (Name => 'a', Ownerref => P);
P.all := (Name => 'p', Animalref => A);
Put_Line (P.Name & " owns " & P.Animalref.Name);
Put_Line (A.Name & " is owned by " & A.Ownerref.Name);
end Animals_And_Persons;

编译和运行时给出
$ ./animals_and_persons 
p owns a
a is owned by p

关于艾达:如何解决 "Circular Unit Dependency"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34694211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com