Ada:范围 1..var 中的自定义类型?
Ada : custom type in range 1..var?
我是 Ada 代码的初学者。我使用 AdaCore 的 GPS。
我会创建一个由用户决定大小的变量。
我这样写:
-- My ada program --
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure main is
wanted : Integer := 10;
type custom is range 0..wanted;
...
但是第 8 行出了点问题:
Builder results
C:\Users\**********\Desktop\ada project\src\main.adb
8:26 "wanted" is not static constant or named number (RM 4.9(5))
8:26 non-static expression used for integer type bound
我真的不明白这是什么意思...有人可以帮我吗?
变量wanted
不是常量,它可能在程序执行过程中改变其值,因此在声明新类型时不允许将此变量用作范围约束。但是,您可以使用 constant
关键字 (Wanted : constant Integer := 10;
) 使其保持不变。它应该可以解决您的问题。
正如 Timur 所说,wanted 必须在其范围内保持不变。这允许您做一些不错的事情,例如在过程中声明类型。看看这个,它可能会很有趣:)
-- My ada program --
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure Main is
procedure Test (Wanted : Integer) is
type custom is new Integer range 0..wanted;
begin
Put_Line("First value " & Custom'Image (Custom'First)
& " Last value " & Custom'Image (Custom'Last));
end Test;
begin
Test (10);
Test (12);
end Main;
输出是
First value 0 Last value 10
First value 0 Last value 12
在这种情况下,您的类型不同于对另一个调用的类型,但它的工作原理是 wanted 在过程中是不变的。唯一的问题是定义的类型必须是您的参数类型的新派生类型。
我让你想想可能性:)
我是 Ada 代码的初学者。我使用 AdaCore 的 GPS。
我会创建一个由用户决定大小的变量。 我这样写:
-- My ada program --
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure main is
wanted : Integer := 10;
type custom is range 0..wanted;
...
但是第 8 行出了点问题:
Builder results
C:\Users\**********\Desktop\ada project\src\main.adb
8:26 "wanted" is not static constant or named number (RM 4.9(5))
8:26 non-static expression used for integer type bound
我真的不明白这是什么意思...有人可以帮我吗?
变量wanted
不是常量,它可能在程序执行过程中改变其值,因此在声明新类型时不允许将此变量用作范围约束。但是,您可以使用 constant
关键字 (Wanted : constant Integer := 10;
) 使其保持不变。它应该可以解决您的问题。
正如 Timur 所说,wanted 必须在其范围内保持不变。这允许您做一些不错的事情,例如在过程中声明类型。看看这个,它可能会很有趣:)
-- My ada program --
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure Main is
procedure Test (Wanted : Integer) is
type custom is new Integer range 0..wanted;
begin
Put_Line("First value " & Custom'Image (Custom'First)
& " Last value " & Custom'Image (Custom'Last));
end Test;
begin
Test (10);
Test (12);
end Main;
输出是
First value 0 Last value 10
First value 0 Last value 12
在这种情况下,您的类型不同于对另一个调用的类型,但它的工作原理是 wanted 在过程中是不变的。唯一的问题是定义的类型必须是您的参数类型的新派生类型。
我让你想想可能性:)