You can declare a pointer to any
type, using the syntax
type pointerTypeName = ^type
When you define a record or other
data type, it’s a common practice also to define a pointer to that type. This
makes it easy to manipulate instances of the type without copying large blocks
of memory.
Standard pointer types exist for
many purposes. The most versatile is Pointer, which can point to data of
any kind. But a Pointer variable cannot be dereferenced; placing the ^
symbol after a Pointer variable causes a compilation error. To access
the data referenced by a Pointer variable, first cast it to another
pointer type and then dereference it.
声明指针类型的语法如下
type pointerTypeName = ^type
定义记录或其他数据类型时,在实际应用中一般也为其定义相应的指针类型。这使得管理这些类型的实例不用复制大块内存,变得简单。
标准指针类型的用途存在多种。最通用的是Pointer,它可以指向任意种类的数据。但是,Pointer变量不能被解除参照,在Pointer变量之后放置 ^ 符号将引发编译错误。要访问Pointer变量被接触参照后的数据,首先要将其转换成另一个能被解除参照的指针类型。
编者注
Object Pascal素有“先声明,后使用”的基本规则,这使得程序结构规范、严谨。但这一规则在某些特殊情况下则不适用。例如,
type
PRec = ^TRec;
TRec = record
ID: Integer;
Next: PRec;
end;
var
A: array of TRec;
这是循环链表典型的声明范例。可以看出,在声明PRec类型时用到了TRec类型,而此时TRec类型尚未被声明。事实上,编译器对上面的声明是认可的,而且只能如此声明。调换PRec和TRec的声明顺序,编译器将不认可。在PRec和TRec的声明之间加入其他类型声明,只要不增加保留字type,编译器也是认可的。简单地说,类似于这样的循环,相互依赖的声明必需位于同一组类型声明中(即由同一个保留字type引出),而且只能是类型指针在声明之前可以被使用,并且必需在本组类型声明结束之前其进行声明。例如,下面的声明也是合法的:
type
PRec = ^TRec;
PA = array of PRec;
TIntA = array of Integer;
TRec = record
ID: Integer;
Next: PRec;
end;
当然,对于非循环的类型指针声明,也可以采用类似声明。下面的两组声明是等价的:
{ 使用时尚未声明 }
type
PRec = ^TRec;
TRec = record
ID: Integer;
Name: string[10];
end;
{ 使用前已经声明 }
type
TRec = record
ID: Integer;
Name: string[10];
end;
PRec = ^TRec;
显然,后面一组声明更符合规范。