【问题标题】:Delphi: Declaring constant record type containing constant arraysDelphi:声明包含常量数组的常量记录类型
【发布时间】:2011-11-18 19:23:00
【问题描述】:

我有很多常量数组都有相同数量的元素。

为了存储这些数组,我声明了一个足够大的数组类型来存储(或引用?)这些数组中最大数组的每个元素:

type
  TElements = array [1 .. 1024] of Single;

这些 TElements 数组中的每一个在逻辑上都与另一个 确实具有相同数量元素的 TElements 数组相关联。

为了将这些大小相等的数组配对,我将记录类型声明为:

type
  TPair = record
    n : Integer; // number of elements in both TElements arrays
    x : ^TElements;
    y : ^TElements;
  end;

然后我定义包含常量 TElements 数组对的常量 TPair 记录:

const

  ElementsA1 : array [1 .. 3] of Single = (0.0, 1.0,  2.0);
  ElementsA2 : array [1 .. 3] of Single = (0.0, 10.0, 100.0);
  ElementsA  : TPair =
  (
    n : 3;
    x : @ElementsA1;
    y : @ElementsA2;
  );

  ElementsB1 : array [1 .. 4] of Single = (0.0, 1.0,  2.0,   3.0);
  ElementsB2 : array [1 .. 4] of Single = (0.0, 10.0, 100.0, 1000.0);
  ElementsB  : TPair =
  (
    n : 4;
    x : @ElementsB1;
    y : @ElementsB2;
  );  

这似乎是引用数组数据的低效方式(也许不是,我不知道)。

我想维护一个包含两个常量数组的常量数据类型(“对”数据类型)。

在每个“对”中,保证两个数组具有相同数量的元素。

但是,不能保证一个“对”中的数组元素数量等于任何其他“对”中的数组元素数量。

有没有办法声明一个常量“对”数据类型,以便包含的数组大小由常量数组定义确定?

理想情况下,我想摆脱 TElements 类型和笨拙的指针。如果它能够编译,这样的东西会很酷:

type
  TPair = record
    x : array of Single; 
    y : array of Single; 
  end;

const

  ElementsA : TPair =
  (
    x : (0.0, 1.0,  2.0);
    y : (0.0, 10.0, 100.0);
  );

  ElementsB : TPair =
  (
    x : (0.0, 1.0,  2.0,   3.0);
    y : (0.0, 10.0, 100.0, 1000.0);
  );

但我猜由于数组被声明为动态数组,它不想在运行前为它们分配内存?

【问题讨论】:

    标签: arrays delphi constants records


    【解决方案1】:

    有没有办法声明一个常量“对”数据类型,以便包含的数组大小由常量数组定义决定?

    不,遗憾的是这是不可能的。您必须在方括号内声明数组的大小。

    【讨论】:

    • 在 XE7+ 中可以声明一个常量多维动态数组:ElementsA : array of array of Single = [[0.0,1.0,2.0],[0.0,10.0,100.0]];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    相关资源
    最近更新 更多