There are
several ways to categorize Object Pascal data types:
· Some types are predefined
(or built-in); the compiler recognizes these automatically, without the
need for a declaration. Almost all of the types documented in this language
reference are predefined. Other types are created by declaration; these include
user-defined types and the types defined in the product libraries.
· Types can be
classified as either fundamental or generic. The range and format
of a fundamental type is the same in all implementations of Object Pascal,
regardless of the underlying CPU and operating system. The range and format of
a generic type is platform-specific and could vary across different
implementations. Most predefined types are fundamental, but a handful of
integer, character, string, and pointer types are generic. It’s a good idea to
use generic types when possible, since they provide optimal performance and
portability. However, changes in storage format from one implementation of a
generic type to the next could cause compatibility problems, for example, if
you are streaming data to a file.
· Types can be classified as simple, string, structured, pointer, procedural, or variant. In addition, type identifiers themselves can be regarded as belonging to a special type because they can be passed as parameters to certain functions (such as High, Low, and SizeOf).
The
outline below shows the taxonomy of Object Pascal data types.
(type identifier)
The
standard function SizeOf operates on all variables and type identifiers.
It returns an integer representing the amount of memory (in bytes) used to
store data of the specified type. For example, SizeOf(Longint) returns 4, since
a Longint variable uses four bytes of memory.
Type declarations are illustrated in the sections that follow. For general information about type declarations, see Declaring types.
Data types and variables: Overview
Type compatibility and
identity: Overview
区分Object Pascal数据类型有下列几种途径:
· 一些预定义类型(或叫内建类型);编译器自动认可这些类型,而不需要声明。几乎所有在当前语言参考中出现的类型都是预定义类型。其他类型都是由声明创建的;包括用户定义的类型和产品包(如VCL)中定义的类型。
· 类型可以分为基本(fundmental)类型和一般(generic)类型。不管基于何种CPU和操作系统,基本类型的范围和格式在Object
Pascal的所有执行中都是相同的。一般类型的范围和格式根据平台的不同而有所区别,并且在不同的执行中也有变化。大部分预定义类型是基本类型,但一小部分的整数、字符、串和指针类型是一般类型。尽可能地使用一般类型是个好主意,因为他们提供了最佳的性能和可移植性。然而,改变一般类型执行的存储格式可能导致兼容性的问题,例如,向文件输入数据流时。
· 类型可以分为简单类型、串类型、结构类型、指针类型、程序型类型、变体类型等。此外,类型标识符自身可以被视为属于某个特定类型,因为他们可以被作为参数传递到某些函数中(如High、Low、SizeOf等)。
下面是Object Pascal数据类型的分类层次图:
(类型标识符)
标准函数SizeOf可以作用于所有的变量和类型标识符,它返回的整数表示的是指定类型用于存储数据所使用内存的字节数。例如,SizeOf(LongInt)返回4,因为一个LongInt变量使用4字节的内存。
后面的章节举例说明了类型声明。有关类型声明的一般信息,见声明类型。
编者注
SizeOf对长串类型总是返回4,如SizeOf(string)总是返回4,而不管串中存放了多少字符。这是因为,Object Pascal根据长串类型的值动态为其管理(分配、释放等)内存,而为长串类型的标识符分配4字节的内存,用于存储串值的地址。同样,SizeOf对宽串类型也总是返回4,如SizeOf(WideString)总是返回4。更多信息见长串。
此外,SizeOf对短串类型总是返回256,而不管串值具体是什么。例如,对于类型为ShortString的变量S,SizeOf(S)总是返回256。这是因为,Object Pascal对短串类型的处理仍沿用传统Pascal的方式,即用短串中索引为0的字符存储串的长度(假定为n,n <= 255),而在索引为1..n的字符中分布存储串值。更多信息见短串。
要获得串的长度,应当使用预定义函数Length。