真C静态局部变量替换? [英] True C static local variable replacement?

查看:85
本文介绍了真C静态局部变量替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅尝试在ObjectPascal / Delphi中实现C / C ++静态局部变量的类似功能。
让我们在C中具有以下功能:

just trying to achieve similar functionality of C/C++ static local variables in ObjectPascal/Delphi. Let's have a following function in C:

bool update_position(int x, int y)
{
    static int dx = pow(-1.0, rand() % 2);
    static int dy = pow(-1.0, rand() % 2);

    if (x+dx < 0 || x+dx > 640)
        dx = -dx;
    ...
    move_object(x+dx, y+dy);
    ...
}

使用类型化常量作为静态对象的等效ObjectPascal代码变量替换无法编译:

Equivalent ObjectPascal code using typed constants as a static variable replacement fails to compile:

function UpdatePosition(x,y: Integer): Boolean;
const
  dx: Integer = Trunc( Power(-1, Random(2)) );  // error E2026
  dy: Integer = Trunc( Power(-1, Random(2)) );
begin
  if (x+dx < 0) or (x+dx > 640) then
    dx := -dx;
  ...
  MoveObject(x+dx, y+dy);
  ...
end;

[DCC错误] test_f.pas(332):E2026需要常量表达式

那么有一种方法可以一次性初始化 local 变量吗?

So is there some way for a one-time pass initialized local variable ?

推荐答案

在Delphi中没有C静态变量的直接等效项。

There's no direct equivalent of a C static variable in Delphi.

可写的类型常量(请参见user1092187的答案)几乎是等效的。它具有相同的作用域和实例化属性,但不允许使用C或C ++静态变量进行一次性初始化。无论如何,我认为应该将可写类型常量作为古朴的历史注脚。

A writeable typed constant (see user1092187's answer) is almost equivalent. It has the same scoping and instancing properties, but does not allow the one-time initialization that is possible with a C or C++ static variable. In any case it is my opinion that writeable typed constants should be shunned as a quaint historical footnote.

您可以使用全局变量。

var
  dx: Integer;
  dy: Integer 

function UpdatePosition(x,y: Integer): Boolean;
begin
  if (x+dx < 0) or (x+dx > 640) then
    dx := -dx;
  ...
  MoveObject(x+dx, y+dy);
  ...
end;

您必须在初始化中进行一次性初始化部分:

initialization
  dx := Trunc( Power(-1, Random(2)) );
  dy := Trunc( Power(-1, Random(2)) );

当然,与C静态变量的有限范围不同,这会使全局名称空间一团糟。在现代的Delphi中,您可以将其全部包装在一个类中,并使用类方法,类vars,类构造器,以避免污染全局名称空间。

Of course this make a mess of the global namespace unlike the limited scope of a C static variable. In modern Delphi you can wrap it all up in a class and use a combination of class methods, class vars, class constructors to avoid polluting the global namespace.

type
  TPosition = class
  private class var
    dx: Integer;
    dy: Integer;
  private
    class constructor Create;
  public
    class function UpdatePosition(x,y: Integer): Boolean; static;
  end;

class constructor TPosition.Create;
begin
  dx := Trunc( Power(-1, Random(2)) );
  dy := Trunc( Power(-1, Random(2)) );
end;

class function TPosition.UpdatePosition(x,y: Integer): Boolean;
begin
  // your code
end;

这篇关于真C静态局部变量替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆