I learned about Delphi and my notes-user-defined data types (Lecture 3)

Source: Internet
Author: User
Tags array definition

An important feature of Pascal is that it can customize data types. With various types of constructors, you can define your own data types, such as subfield type, array type, record type, enumeration type, pointer type, and set type. The most important user-defined data type is class, which is the object-oriented extension of Object Pascal. This part is not discussed in this book.

You may think that other programming languages also have such Type constructor, but Pascal is the first language to perfectly implement this theory. So far, no language can define so many data types.

Naming and non-Naming types

To be used later or directly for variables, You need to name the custom type. If you customize a named type, you must put the code in a specificTypeAs follows:

type  // subrange definition  Uppercase = 'A'..'Z';  // array definition  Temperatures = array [1..24] of Integer;  // record definition  Date = record    Month: Byte;    Day: Byte;    Year: Integer;  end;  // enumerated type definition  Colors = (Red, Yellow, Green, Cyan, Blue, Violet);  // set definition  Letters = set of Char;

You can also use the type definition constructor to directly define a variable without explicit naming. The following code:

var  DecemberTemperature: array [1..31] of Byte;  ColorCode: array [Red..Violet] of Word;  Palette: set ofColors;

Note:: In general, you should avoid using the non-Naming types mentioned above, because you cannot pass them as parameters to routines or use them to name other variables of the same type. In fact, Pascal's type compatibility rules are based on the Type name, rather than the actual type definition. Two variables of the same type may still be incompatible, unless their types have identical names. For a non-naming type, you need the compiler to assign it an internal name. Therefore, for variables with complicated data structures, you must get used to defining the named data type. This will not be a waste of time.

But what is the significance of the above custom type? If you are not familiar with the Pascal Type constructor, you will understand it through the following content. In addition, the differences between similar constructor in different languages are also discussed below, therefore, if you are familiar with the type definition mentioned above, you may wish to read it down and you will be interested in the content. Finally, I will demonstrate some Delphi examples and introduce some tools that can dynamically access type information.

Subfield type
The subinterface type defines the value range of a certain type (Subrange). You can define the subboundary type of the integer type, for example, the value ranges from 1 to 10 or from 100 to 1000, or the subboundary type of the character type, as shown below:
type  Ten = 1..10;  OverHundred = 100..1000;  Uppercase = 'A'..'Z';
When defining a subinterface type, you do not need to specify the base class name, but only need to provide two constants of this type. The base class used must be an ordered type, and the defined result will be another ordered type.
If you define a sub-interface variable, the value assigned to the variable must be within the defined range of the sub-interface. The following code is correct:
var  UppLetter: UpperCase;begin  UppLetter := 'F';
The following code is incorrect:
var  UppLetter: UpperCase;begin  UppLetter := 'e'; // compile-time error
The above code will cause a compilation error:"Constant expression violates subrange bounds".
If you replace the following code:
var  UppLetter: Uppercase;  Letter: Char;begin  Letter :='e';  UppLetter := Letter;
Delphi compilation will pass, but at runtime, If you enable the range check compilation option (set on the compiler page of the Project Options dialog box), you will getRange check error(Range detection error) information.
Note:: We recommend that you enable the above compilation options during program development to make the program more robust and easy to debug. In this way, even if you encounter an error, you will get a clear message instead of an uncertain behavior. When the program is finally completed, you can remove this option to make the program run faster, but the impact is very small. Therefore, we recommend that you enable all runtime detection options, such as overflow check and stack check, and even keep them when submitting programs.
Enumeration type
The enumeration type is also a Custom ordered type. In the enumerated type, you list all possible values of this type, rather than specifying the range of the existing type. In other words, the enumeration type is a sequence of optional values. See the following example:
type  Colors = (Red, Yellow, Green, Cyan, Blue, Violet);  Suit = (Club, Diamond, Heart, Spade);
Each value in the sequence corresponds to a sequence number, which starts from 0. UseOrdFunction to obtain the serial number of an enumerated value. For example,Ord (Diamond)Return Value 1.
Note:: Enumeration types have multiple internal representations. Time-saving. Delphi uses 8-bit notation. If there are more than 256 different values, it uses 16-bit notation. There is also a 32-bit notation that will be used when it is compatible with C and C ++ libraries. Use$ ZCompile the command to change the default settings and request more bits.
Set Type

The set type indicates a group of values, which are defined by the sorted type of the set. There are not many common order types for defining a set, which are generally enumeration or subfield types. If the value of the subfield type is 1 .. 3, then the set type value based on it can be 1, 2, or 3, or 1 and 2, or 1 and 3, or 2 and 3, or take all three numbers, or one no.

A variable usually contains a value corresponding to this type. A set type can contain no value, one value, two values, three values, or more, it can even contain all values within the defined range. The following defines a set:

type  Letters = set of Uppercase;

Now I can use the above type to define the variable and assign the value of the original type to the variable. To represent a group of values in a set, use commas to separate the values and end with square brackets. The following example shows how to assign values to multiple values, single values, and null values:

var  Letters1, Letters2, Letters3: Letters;begin  Letters1 := ['A', 'B', 'C'];  Letters2 := ['K'];  Letters3 := [];

In Delphi, a set is generally used to indicate tags with multiple options. For example, the following two lines of code (from the Delphi Database) Declare An Enumeration type, which lists the optional icons on the window bar and declares the corresponding collection type:

type  TBorderIcon = (biSystemMenu, biMinimize, biMaximize, biHelp);  TBorderIcons = set of TBorderIcon;
Array type

The array type defines a sequence of elements of the specified type. You can access the elements in the array by entering the following values in square brackets. When defining an array, square brackets are also used to specify possible subscript values. For example, the following code defines an array with 24 integers:

type  DayTemperatures = array [1..24] of Integer;

When defining an array, you need to fill in a value of the subfield type in square brackets, or use two constants of the ordered type to define a new subfield type, the subfield type specifies the valid index of the array. Since the subfield type specifies the upper and lower bounds of the array lower mark values, the subscript does not have to start from scratch like C, C ++, JAVA and other languages.

Since the array subscript is based on the subinterface type, Delphi can check their range. An invalid constant quantum field type will result in a compilation time error. If the compiler range check option is selected, an out-of-range value will lead to a running time error.

Use the preceding array definition method to defineDayTemperaturesType variables are as follows:

type  DayTemperatures = array [1..24] of Integer;var    DayTemp1: DayTemperatures;  procedure AssignTemp;  begin    DayTemp1 [1] := 54;  DayTemp1 [2] := 52;  ...  DayTemp1 [24] := 66;  DayTemp1 [25] := 67; // compile-time error

Arrays can be multidimensional, as shown in the following example:

type  MonthTemps = array [1..24, 1..31] of Integer;  YearTemps = array [1..24, 1..31, Jan..Dec] of Integer;

These two arrays are built on the same core type, so you can declare them with the data types defined above, as shown in the following code:

type  MonthTemps = array [1..31] of DayTemperatures;  YearTemps = array [Jan..Dec] of MonthTemps;

The statement in the preceding example changes the index order, but the entire value can still be assigned between variables. For example, assign the temperature value of January to January:

var  ThisYear: YearTemps;begin  ...  ThisYear[Feb] := ThisYear[Jan];

You can also define the array whose subscript starts from scratch, but this does not seem logical, because you need to use subscript 2 to access the third item of the array. However, Windows has always followed the array starting from scratch (because it is based on the C language), and the Delphi control library is also moving closer in this direction.

When using arrays, you always use standard functions.LowAndHighTo detect its boundary,LowAndHighReturns the lower and upper bounds of the lower mark. We strongly recommend that you useLowAndHighOperate the array, especially in the loop, because this will make the code irrelevant to the array range. If you change the range declaration under the array,LowAndHighThe code will not be affected; otherwise, if the Code contains an array subscript loop body, you will have to update the code of the loop body when the array size changes.LowAndHighThis will make your code easier to maintain and more stable.

Note:: By the way, useLowAndHighDoes not increase additional system running overhead. Because they have been converted into constant expressions during compilation, rather than actual function calls. This is also true for other simple system functions.

Record type

The record type is used to define a fixed set of different types of data items. Each element or field in the record has its own type. All domains are listed in the record type definition. Each domain corresponds to one domain name and can be accessed through the domain name.

The following briefly lists the definition of record types, the declaration of type variables, and the use of such variables:

type  Date = record    Year: Integer;    Month: Byte;    Day: Byte;  end;  var  BirthDay: Date;  begin  BirthDay.Year := 1997;  BirthDay.Month := 2;  BirthDay.Day := 14;

Classes and objects can be seen as extensions of record types. The Delphi library tends to replace record types with classes, but many record types are defined in Windows APIs.

The record type can contain the variant field, which indicates that multiple domains can share the same memory zone, and the field can be of different types (which corresponds to the union in C ). In other words, you can access the same memory location through the variant domain or a group of domain access records, but each value still needs to be treated differently. The variant type is mainly used to store similar but different data and perform type conversion similar to typecasting (this method is rarely used since the introduction of typecasting to Pascal ). Although Delphi still uses the variant record type in some special cases, it is now replaced by object-oriented technology or other modern technology.

Applications of the variant record type do not comply with the type security principles, so they are not recommended for programming. This is especially true for beginners. In fact, expert programmers really need to use the variant record type, which is used in the core part of the Delphi Database. However, unless you are a Delphi expert, you should avoid using the variant record type.

Pointer

A pointer is a variable that stores the memory address of a specified type (or undefined type) variable. Therefore, a pointer indirectly references a value. Define a pointer using a special character instead of a specific keyword. This special character is a delimiters (^), as shown in the following example:

type  PointerToInt = ^Integer;

Once you define a pointer variable, you can use the @ symbol to assign the address of another variable of the same type to it. See the following example:

var  P: ^Integer;  X: Integer;begin  P := @X;  // change the value in two different ways  X := 10;  P^ := 20;  

If a pointer P is defined, P indicates the memory address pointed to by the pointer, and P ^ indicates the actual content stored in the memory. Therefore, in the above Code, P ^ is equal to X.

In addition to the address indicating the allocated memory, the pointer can also passNewThe routine dynamically allocates memory in the heap. However, when you do not need this pointer, you must also callDisposeThe routine releases your dynamically allocated memory.

Delphi also definesPointerData type, which indicates a non-typed pointer (just likeVoid *). If you use a non-type pointer, you should useGetMemRoutine insteadNewRoutine, becauseGetMemRoutines can be used when the memory allocation size is uncertain.

In fact, pointer must be used in Delphi, which is an attractive advantage of the Delphi development environment. Even so, it is important to understand the pointer to perform advanced programming and fully understand the Delphi object model, because the Delphi object model uses the pointer behind the scenes.

Note:: Although pointers are not often used in Delphi, you often use a very similar structure-references ). Each object instance is actually an implicit pointer, or a reference to its actual data. With reference, you can use object variables like other data types.

File Type

Another Pascal-specific Type constructor is a file type (File). The file type represents a physical disk file, which is undoubtedly a special type of Pascal Language. In the following method, you can define a new data type:

type  IntFile = file of Integer;

Then, you can open a physical file corresponding to the structure, write Integers to the file, or read the current value from the file.

The use of Pascal file types is intuitive, and Delphi also defines some controls for file storage and loading, as well as support for data streams and databases.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.