gpt4 book ai didi

compiler-errors - Ada - 一维数组操作

转载 作者:行者123 更新时间:2023-12-04 07:06:41 24 4
gpt4 key购买 nike

引用约翰巴恩斯的书“Ada 2012 中的编程”(ISBN:978-1-107-42481-4),第138 页(第8.6 节)。

procedure ArrayOps is
type Bit_Row is array (Positive range <>) of Boolean;

A, B : Bit_Row (1 .. 4);

T : constant Boolean := True;
F : constant Boolean := False;
begin
A := (T, T, F, F);
B := (T, F, T, F);

A := A and B;
end ArrayOps;

我在作者提供的最小片段周围添加了一个简单的包装器,这似乎可以按预期编译和运行。

作者指出这可以通过“许多运算符”来完成,暗示算术,例如 + , * , -/ .

我试图使用整数数据类型将其转换为加法运算符,但可惜这不能编译......

procedure ArrayOps is
type Int_Row is array (Positive range <>) of Integer;

A, B : Int_Row (1 .. 4);

T : constant Integer := 1;
F : constant Integer := 0;
begin
A := (T, T, F, F);
B := (T, F, T, F);

A := A + B;
end ArrayOps;

编译器错误状态: arrayops.adb:12:10: there is no applicable operator "+" for type "Int_Row" defined at line 2 .这是唯一的错误。很明显,我的代码中缺少一些东西,但是这本书再也没有提到这个话题。如何为 bool 运算符以外的运算符启用数组操作?

编辑:

我已经按照@egilhh 的回答修改了代码,因为这似乎是解决基本问题的最小更改集。
procedure ArrayOps is
type Int_Row is array (1 .. 4) of Integer;

function "+"(Left, Right : Int_Row) return Int_Row
is
Result : Int_Row;
begin
for I in Int_Row'Range loop --'
Result(I) := Left(I) + Right(I);
end loop;
return Result;
end "+";

A, B : Int_Row;

T : constant Integer := 1;
F : constant Integer := 0;
begin
A := (T, T, F, F);
B := (T, F, T, F);

A := A + B;
end ArrayOps;

这现在有效。但是,我接受了 DeeDee 的回答,因为这可能是最佳实践解决方案。两个都点赞 :)

最佳答案

书中的“许多运算符”指的是逻辑运算符和关系运算符。只有这些运算符是按照语言标准的要求为一维数组类型隐式定义的(参见 RM 4.5.1 (2)RM 4.5.2 (1))。

对于其他运算符,您需要自己实现它们:

arrayops.adb

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO;

procedure ArrayOps is

type Int_Row is array (Positive range <>) of Integer;

A, B : Int_Row (1 .. 4);

T : constant Integer := 1;
F : constant Integer := 0;

---------
-- "+" --
---------

function "+" (A, B : Int_Row) return Int_Row is
begin

if A'Length /= B'Length then
raise Constraint_Error with "array lengths do not match";
end if;

declare
Result : Int_Row (1 .. A'Length);
begin
for I in Result'Range loop
Result (I) := A (A'First + I - 1) + B (B'First + I - 1);
end loop;
return Result;
end;

end "+";

---------
-- Put --
---------

procedure Put (A : Int_Row; Width : Natural := 0) is
use Ada.Integer_Text_IO;
begin
for I in A'Range loop
Put (A (I), Width);
end loop;
end Put;

begin

A := (T, T, F, F);
B := (T, F, T, F);

Put (A, 2); New_Line;
Put (B, 2); New_Line;

A := A + B;

Put ("--------- +"); New_Line;
Put (A, 2); New_Line;

end ArrayOps;

输出
 1 1 0 0
1 0 1 0
--------- +
2 1 1 0

关于compiler-errors - Ada - 一维数组操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615272/

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