arrays - 创建字符串数组 - Const 表达式预期错误

标签 arrays delphi

我在这个 Delphi 程序的 var 部分中声明了两件事:

  LCloneTask1, LCloneTask2, LCloneTask3, ... , LCloneTask20 : String;
  CloneTaskArray : array[0..19] of String = (LCloneTask1, LCloneTask2, LCloneTask3,.., LCloneTask20);

其中第一行声明一些字符串,第二行声明所述字符串的数组。该数组的大小始终为 20。

当我尝试编译时,出现错误“需要常量表达式”。我没有正确声明字符串数组吗?我需要能够稍后在程序中读取和写入该数组。

最佳答案

您正在尝试将变量初始化作为其声明的一部分。 documentation声明语法必须是:

var identifier: type = constantExpression;

where constantExpression is any constant expression representing a value of type type.

documentation for constant expressions说(强调我的):

A constant expression is an expression that the compiler can evaluate without executing the program in which it occurs. Constant expressions include numerals; character strings; true constants; values of enumerated types; the special constants True, False, and nil; and expressions built exclusively from these elements with operators, typecasts, and set constructors. Constant expressions cannot include variables, pointers, or function calls.

您违反了最后一句话,特别是我强调的部分。


您很可能只想声明一个字符串数组。在这种情况下,您只需编写:

var
  CloneTaskArray: array[0..19] of string;

如果您需要初始化此数组,请在声明它们的单元的初始化部分中执行此操作:

initialization
  CloneTaskArray[0] := 'boo';
  CloneTaskArray[1] := 'yah';
  ....

我注意到您正在尝试使用其他字符串变量初始化数组的元素。举一个更简单的例子,我想知道你是否正在尝试这样做:

var
  s1, s2: string;
  StringArray: array[0..1] of string;
....
StringArray[0] := s1; 
StringArray[1] := s2; 

然后我想知道您是否希望能够做到这一点:

s1 := 'boo';
Assert(StringArray[0] = 'boo');

如果这就是你所希望的,你会失望的。 Delphi 中的字符串数据类型相当复杂,但从根本上讲,它的行为类似于值类型。如果您尝试执行我上面概述的操作,则需要使用对字符串变量的引用:

type
  PString = ^string;
var
  s1, s2: string;
  StringArray: array[0..1] of PString;
....
StringArray[0] := @s1; 
StringArray[1] := @s2; 

然后你确实可以写:

s1 := 'boo';
Assert(StringArray[0]^ = 'boo');

关于arrays - 创建字符串数组 - Const 表达式预期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16285710/

相关文章:

php - PDO fetchAll 不返回所有行

c - 整数数组的深拷贝,仅使用指针算法

linux - Indy 10 TCPServer 不与 Linux 上连接的客户端通信

delphi - Error Insight 有键盘快捷键吗?

delphi - 用于Delphi XE2的Windows和Mac XML库

c - Malloc 和 Realloc 结构数组

javascript - es6 具有集合的唯一对象数组

java - 我不明白为什么它说 ArrayOutOfBound 错误

delphi - 标准用户(XP/Server 2003及以下)如何获取所有正在运行的进程的镜像路径?

delphi - 如果 Delphi 库使用 Random,它是否应该避免调用 Randomize 本身?