gpt4 book ai didi

delphi - 在过程和函数中声明参数的不同方式

转载 作者:行者123 更新时间:2023-12-03 18:16:34 25 4
gpt4 key购买 nike

我注意到不同的代码以不同的方式声明参数,我想知道这样做是否有特定的原因,或者这是否是一种偏好。

假设我写了这个函数(只是一个带有不同参数的例子)

function DoSomething(AHeight, AWidth: Integer; R: TRect): Boolean
begin
//
end;

如果它是这样声明的,这有什么不同:

function DoSomething(var AHeight, AWidth: Integer; const R: TRect): Boolean
begin
//
end;

我知道变量是可读/可写的,而常量是只读的,但以这种方式声明参数有何不同?

对我来说,这两个函数都在寻找调用代码来提供高度、宽度和矩形,但是第二个函数让它看起来像是在声明新变量。

我觉得这将是一个非常直接的答案,我觉得问这个问题很愚蠢,但我必须知道有什么区别,如果有的话?

最佳答案

documentation解释得很清楚:

Most parameters are either value parameters (the default) or variable (var) parameters. Value parameters are passed by value, while variable parameters are passed by reference. To see what this means, consider the following functions:

function DoubleByValue(X: Integer): Integer;   // X is a value parameter
begin
X := X * 2;
Result := X;
end;

function DoubleByRef(var X: Integer): Integer; // X is a variable parameter
begin
X := X * 2;
Result := X;
end;

These functions return the same result, but only the second one - DoubleByRef can change the value of a variable passed to it. Suppose we call the functions like this:

var
I, J, V, W: Integer;
begin
I := 4;
V := 4;
J := DoubleByValue(I); // J = 8, I = 4
W := DoubleByRef(V); // W = 8, V = 8
end;

After this code executes, the variable I, which was passed to DoubleByValue, has the same value we initially assigned to it. But the variable V, which was passed to DoubleByRef, has a different value.

A value parameter acts like a local variable that gets initialized to the value passed in the procedure or function call. If you pass a variable as a value parameter, the procedure or function creates a copy of it; changes made to the copy have no effect on the original variable and are lost when program execution returns to the caller.

A variable parameter, on the other hand, acts like a pointer rather than a copy. Changes made to the parameter within the body of a function or procedure persist after program execution returns to the caller and the parameter name itself has gone out of scope.

Even if the same variable is passed in two or more var parameters, no copies are made. This is illustrated in the following example:

procedure AddOne(var X, Y: Integer);
begin
X := X + 1;
Y := Y + 1;
end;

var I: Integer;
begin
I := 1;
AddOne(I, I);
end;

After this code executes, the value of I is 3.


我建议您添加指向 Delphi Language guide 的链接到浏览器的书签。

关于delphi - 在过程和函数中声明参数的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11646615/

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