改变变量指针

2024-03-24

给定 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,我建议您使用您自己的类来操作它们的对象。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

改变变量指针 的相关文章

随机推荐