gpt4 book ai didi

delphi - 为什么编译器拒绝使用 "E2026 Constant expression expected"的常量默认参数值?

转载 作者:行者123 更新时间:2023-12-03 15:51:46 32 4
gpt4 key购买 nike

以下代码无法编译,并显示 [dcc32 错误] TestDefaultParameterValuePrj.dpr(13): E2026 需要常量表达式:

program TestDefaultParameterValuePrj;

{$APPTYPE CONSOLE}

{$R *.res}

uses
System.SysUtils;

const
SomeValue: char = 'T';

function Test(p1: String; p2: char = SomeValue): String;
begin
Result := p2;
end;

begin
try
Writeln(Test('Blah Blah'));
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.

基于此thread如果我真的想使用常量,我可以使用重载函数。然而,令我惊讶的是编译器不接受它。

最佳答案

来自documentation ,我强调的是:

You can specify default parameter values in a procedure or function heading. Default values are allowed only for typed const and value parameters. To provide a default value, end the parameter declaration with the = symbol followed by a constant expression that is assignment-compatible with the parameter's type.

类型常量不是常量表达式。将您的常量声明为真正的常量,它是一个常量表达式:

const
SomeValue = 'T';

这里讨论了真正的常量、类型化常量和常量表达式的棘手问题:Declared Constants 。一些关键摘录:

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.

....

This definition of a constant expression is used in several places in Delphi's syntax specification. Constant expressions are required for initializing global variables, defining subrange types, assigning ordinalities to values in enumerated types, specifying default parameter values, writing case statements, and declaring both true and typed constants.

....

Typed constants, unlike true constants, can hold values of array, record, procedural, and pointer types. Typed constants cannot occur in constant expressions.

关于delphi - 为什么编译器拒绝使用 "E2026 Constant expression expected"的常量默认参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34818333/

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