改变变量指针 [英] Change pointer of variables
问题描述
给定 2 个变量(布尔值、整数、int64、TDateTime 或字符串),如何将 A 设置为始终指向 B?
Given 2 variables (either boolean, integer, int64, TDateTime or string), how can I set A to always point to B?
假设 A 和 B 是整数,我将 B 设置为 10.
Let's say A and B are integers, I set B to 10.
从这里开始,我希望 A 始终指向 B,因此如果我执行 A := 5
它将改为修改 B.
From here on I want A to always point to B, so if I do A := 5
it will modify B instead.
我希望能够在运行时执行此操作.
I want to be able to do this at runtime.
推荐答案
有几种方法,如果理解变量是什么:指向内存的指针,所有方法都是显而易见的.
There are several ways, and all of them are obvious if one understands what a variable is: a pointer to memory.
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,我建议您使用您自己的类来操作它们的对象.
Most commonly pointers are used, but also have the most disadvantages (especially if you're not a disciplined programmer). Since you're using Delphi I recommend using your own classes to then operate on objects of them.
这篇关于改变变量指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!