改变变量指针

Change pointer of variables

给定 2 个变量(布尔值、整数、int64、TDateTime 或字符串),如何将 A 设置为始终指向 B?

假设A和B是整数,我把B设为10。

从现在开始我希望 A 始终指向 B,所以如果我这样做 A := 5 它会修改 B。

我希望能够在运行时执行此操作。

有几种方法,如果理解变量是什么:指向内存的指针,所有这些方法都是显而易见的。

使用指针

var
  iNumber: Integer;   // Our commonly used variables 
  sText: String;
  bFlag: Boolean;

  pNumber: PInteger;  // Only pointers
  pText: PString;
  pFlag: PBoolean;
begin
  pNumber:= @iNumber;  // Set pointers to the same address of the variables
  pText:= @sText;
  pFlag:= @bFlag;

  // Change the memory that both variable and pointer link to. No matter if
  // you access it thru the variable or the pointer it will give you the
  // same content when accessing it thru the opposite way.
  pNumber^:= 1138;     // Same as   iNumber:= 1138;
  sText:= 'Content';   // Same as   pText^:= 'Content';
  pFlag^:= TRUE;       // Same as   bFlag:= TRUE;

使用对象

type
  TMyVars= class( TObject )
    iNumber: Integer;
    sText: String;
    bFlag: Boolean;
  end;

var
  oFirst, oSecond: TMyVars;

begin
  oFirst:= TMyVars.Create();   // Instanciate object of class
  oSecond:= oFirst;            // Links to same object

  // An object is already "only" a pointer, hence it doesn't matter through
  // which variable you access a property, as it will give you always the
  // same content/memory.
  oFirst.iNumber:= 1138;       // Same as   oSecond.iNumber:= 1138;
  oSecond.sText:= 'Content';   // Same as   oFirst.sText:= 'Content';
  oFirst.bFlag:= TRUE;         // Same as   oSecond.bFlag:= TRUE;

使用声明

var
  iNumber: Integer;
  sText: String;
  bFlag: Boolean;

  iSameNumber: Integer absolute iNumber;
  iOtherText: String absolute sText;
  bSwitch: Boolean absolute bFlag;
begin
  // Pascal's keyword "absolute" makes the variable merely an alias of
  // another variable, so anything you do with one of both also happens
  // with the other side.
  iNumber:= 1138;            // Same as   iSameNumber:= 1138;
  sOtherText:= 'Content';    // Same as   sText:= 'Content';
  bFlag:= TRUE;              // Same as   bSwitch:= TRUE;

最常用的指针,但也有最多的缺点(特别是如果你不是一个有纪律的程序员)。由于您使用的是 Delphi,我建议您使用自己的 类 然后对它们的对象进行操作。