Wos*_*ame 4 compiler-errors ada
参考约翰·巴恩斯(John Barnes)的《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;
Run Code Online (Sandbox Code Playgroud)
我为作者提供的最小片段添加了一个简单的包装器,它似乎可以按预期进行编译和运行。
作者指出,这可能与“许多运营商的”来完成,这意味着算术比如+,*,-和/。
我试图使用Integer数据类型将其转换为加法运算符,但可惜它无法编译...
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;
Run Code Online (Sandbox Code Playgroud)
编译器错误状态:arrayops.adb:12:10: there is no applicable operator "+" for type "Int_Row" defined at line 2。那是唯一的错误。显然,我的代码中缺少某些内容,但是本书没有再提及此主题。如何为布尔运算符以外的其他运算符启用数组运算?
我已经按照@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;
Run Code Online (Sandbox Code Playgroud)
现在可以使用了。但是,我接受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;
Run Code Online (Sandbox Code Playgroud)
输出
1 1 0 0
1 0 1 0
--------- +
2 1 1 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |