⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch02.htm

📁 delphi自学的好教材!特别适合刚刚起步学习delphi的人员!同样对使用者具有参考价值!
💻 HTM
📖 第 1 页 / 共 5 页
字号:
17:   public18:     { Public declarations }19:   end;20:21: var22:   Form1: TForm1;23:24: implementation25:26: var27:   X : Integer;2829: {$R *.DFM}30:31: procedure TForm1.Button1Click(Sender: TObject);32: var33:   X : Integer;34:35:   procedure Test;36:   var37:     X : Integer;38:   begin39:     X := 300;40:     { This X variable has a value of 300. }41:     Memo1.Lines.Add(`Local Function X: ` + IntToStr(X));42:   end;43:44: begin45:   X := 100;46:   Memo1.Lines.Clear;47:   { Local X has a value of 100. }48:   Memo1.Lines.Add(`Local X: ` + IntToStr(X));49:   { Unit scope X has a value of 200. }50:   Memo1.Lines.Add(`Global X: ` + IntToStr(ScopeU.X));51:   { Call the Test procedure. }52:   Test;53: end;54:55: procedure TForm1.FormCreate(Sender: TObject);56: begin57:   { Initialize the unit variable X. }58:   X := 200;59: end;60:61: end.</PRE><PRE>The first thing you might notice (if you're still awake by this time) is that the variable X is declared three times in this program. It is declared on line 27 in the implementation section, it is declared on line 33 in the Button1Click method, and it is declared on line 37 in a Local Procedure called Test. If you accidentally declare a variable more than once, the compiler spits out an error that says Identifier redeclared: `X', and the compile stops. Yet this program compiles and runs just fine. Why? Because each of the X variables in Listing 2.1 has different scope.</PRE><P>Take a closer look at Listing 2.1. The declaration for X on line 37 is insidethe local procedure Test and is local to that block of code. (I realize I haven'ttalked about local functions and procedures yet so I'm getting a bit ahead of myselfagain. Bear with me; I explain local functions later in the section &quot;Local Functionsand Procedures.&quot;) Effectively, the X that is declared on line 37 does not existoutside the Test procedure. This variable has local scope. Likewise, the declarationfor X on line 33 is local to the Button1Click method and does not exist outside thefunction.</P><P>Now look at the variable X declared in the implementation section. This variableis visible anywhere in this unit. Think about that for a minute. Once inside theButton1Click procedure, there are two variables named X (the one declared in theimplementation section and the one declared in the Button1Click method), and bothare in scope. Which one is being used? The answer: the one in the Button1Click method,because it has the most immediate scope.</P><P>The variable X that is declared in the implementation section is said to have<I>unit scope</I>. What this means is that this variable X is available anywherein the unit. As mentioned earlier, a local variable has precedence over a variablewith unit scope. But what if you want to access the unit variable X from inside theButton1Click procedure and not the local variable X? You can <I>qualify</I> the variable.Line 50 of Listing 2.1 contains this line:</P><P><PRE>Memo1.Lines.Add(`Global X: ` + IntToStr(ScopeU.X));</PRE><P>As you can see, the variable X is qualified with the unit name (ScopeU) followedby the dot operator. Qualifying the variable with the unit name says, &quot;Giveme the unit variable X and not the local variable X.&quot; (The dot operator is alsoused with records and classes, but I'll get to that when I talk about classes later.)</P><P>As I said, when the unit variable X is declared in the implementation section,it has unit scope. If you want a variable to be available to other units in the project,you should declare the variable in the interface section (the variable Form1 in Listing2.1 is declared in this way). A variable declared in the interface section can beaccessed from other units in the project. A variable declared in this way is oftenreferred to as a <I>global variable</I>. To access a variable declared in the interfacesection of a unit requires nothing more than adding the unit to the uses list andaccessing the variable as you would any other variable. If any units in the projecthave variables with the same name, the variables can be qualified with the unit nameas described earlier.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> I just said that a variable declared in a unit's interface section	is usually referred to as a global variable. That's not entirely accurate, though,	because the variable cannot be automatically used by other units in the project--you	have to add the unit containing the variable to the uses list of any other unit that	wants to use the variable. A true global variable is a variable that can be used	by any unit in the program without the need to add the unit containing the variable	to the uses list. Delphi has a few global variables set up by the compiler's startup	code. You cannot declare true global variables yourself. <HR></BLOCKQUOTE><P><H2><A NAME="Heading13"></A>Records</H2><P>A <I>record</I> is a collection of related data rolled up into a single storageunit. For instance, let's say you want to keep a mailing list. It would be convenientto use a single data variable to hold all the fields needed in a typical mailinglist. A record enables you to do that. You first declare the record and then latercreate an instance of that record when you want to use the record. A record is declaredwith the record keyword:</P><P><PRE>MailingListRecord = record  FirstName : string;  LastName : string;  Address : string;  City : string;  State : string;  Zip : Integer;end;</PRE><P>Each of the elements in a record is called a <I>field</I>. Notice that each ofthe fields must be declared just as if it were a variable in a code block. This recordexample has five string fields and one integer field. (My apologies to my friendsaround the world if this looks like a U.S.-slanted mailing-list record.) A zip code/postalcode field should really be a string as well, but I want to show you a record withmore than one data type.</P><P>A <I>record</I> is a collection of related data identified as a single storageunit. After a record is declared, an instance of that record can be created for use.Each of the elements in a record is called a <I>field</I>.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> The record in this example is fine for what I am doing here, but	it is not ideal for storing records in files. When you store records in files, each	record should be of the exact same size in bytes. Because the record in this example	uses long strings as fields, there is no way to guarantee that the records will all	be the same size. When creating records that will be stored in a file, you should	use short strings or even an array of Char over long strings. I'll talk about this	more tomorrow when I discuss file input and output in the section &quot;Dealing with	Binary Data.&quot; <HR></BLOCKQUOTE><P>Now that the record is declared, it can be put to use. I first need to createan instance of the record. Here's how that looks:</P><P><PRE>var  MLRecord : TMailingListRecord;</PRE><P>This statement allocates memory for the record and assigns that memory to a variablenamed Record. Now that I have an instance of the record set up, I can assign valuesto the fields:</P><P><PRE>MLRecord.FirstName := `Bruce';MLRecord.LastName  := `Reisdorph';MLRecord.Address   := `123 Inspiration Pt.';MLRecord.City      := `Merced';MLRecord.State     := `CA';MLRecord.Zip       := 99999;</PRE><P>This code snippet contains some syntax you haven't seen yet (although it is verysimilar to earlier examples when I was discussing qualifying variables). To accessthe fields of a record, you need to employ the <I>structure member selector</I> operator,commonly called the dot operator. The dot operator is a period placed between thevariable name and the field name. If you forget to add the record member operator,you will probably find the compiler complaining about undefined symbols. The recordmember operator enables you to access a particular member of the record--either toread the value of the field or to change the value of the field. Here's an exampleof placing the contents of a particular field in a record into an label on a form:</P><P><PRE>Label1.Caption := MLRecord.LastName;</PRE><H4>The record Statement</H4><PRE><I>name</I> = record    <I>field_1 </I>: <I>data_type</I>;    <I>field_2 </I>: <I>data_type</I>;    .    .    .    <I>field_n</I> : <I>data_type</I>;end;</PRE><P>The record statement declares a grouping of fields (<I>field_1</I>, <I>field_2</I>,..., <I>field_n</I>) and provides a name for this grouping (<I>name</I>).</P><P><H3><A NAME="Heading14"></A>The with Statement</H3><P>As long as I am talking about records, let me introduce the with statement. Useof the with statement is not limited to records, but this is a good place to illustratehow the with statement is used. Earlier I gave you this example of filling in a structure:</P><P><B>MLRecord.FirstName := `Bruce';</B></P><P><PRE>MLRecord.LastName  := `Reisdorph';MLRecord.Address   := `123 Inspiration Pt.';MLRecord.City      := `Merced';MLRecord.State     := `CA';MLRecord.Zip       := 99999;</PRE><P>The with statement can be used to help simplify this code. Here is the same code,but implementing the with statement:</P><P><PRE>with MLRecord do begin  FirstName := `Bruce';  LastName  := `Reisdorph';  Address   := `123 Inspiration Pt.';  City      := `Merced';  State     := `CA';  Zip       := 99999;end;</PRE><P>The with statement says, &quot;With this object (MLRecord) do the following....&quot;Notice that when the with statement is implemented, you no longer have to qualifythe field names with the record identifier and dot operator. Everything within thebegin and end blocks is assumed to belong to the MLRecord object, so qualifying thefield names is unnecessary. The with statement can save you a lot of typing and canalso make the code more readable.</P><P><H3><A NAME="Heading15"></A>Arrays of Records</H3><P>Just as you can have arrays of Integers, Chars, or Words, you can also have arraysof records. Declaring and using an array of records is not terribly complicated:</P><P><PRE>var  MLRecord : array [0..9] of MailingListRecord;begin  MLRecord[0].FirstName := `Bruce';  MLRecord[0].LastName  := `Reisdorph';  MLRecord[0].Address   := `123 Inspiration Pt.';  MLRecord[0].City      := `Merced';  MLRecord[0].State     := `CA';  MLRecord[0].Zip       := 99999;  MLRecord[1].FirstName := `Georgia';  MLRecord[2].LastName  := `Burleson';  MLRecord[3].Address   := `999 Fortitude';  MLRecord[4].City      := `Denver';  MLRecord[5].State     := `C0';  MLRecord[6].Zip       := 80888;  Label1.Caption := MLRecord[0].LastName;  { More code here. }end;</PRE><P>This is only slightly more complicated than using an array of one of the integraldata types. You will notice that the subscript operator and the record member operatorare used together to retrieve the value of a field from a specific position in thearray.</P><P><H3><A NAME="Heading16"></A>Include Files</H3><P>Sometimes Pascal programmers use include files. An include file can contain anycode that you don't want in your main source unit. Typically, use of include filesis reserved for constants or compiler directives that are intended to be used bymany other files in the project. An include file is nothing more than a text filewith and extension of .INC. The INC extension is not a requirement, but it is customary.Listing 2.2 shows an example of an include file.</P><P><H4>LISTING 2.2. TEST.INC.</H4><PRE>const  DefWidth  = 500;  DefHeight = 300;type  MailingListRecord = record    FirstName : string;    LastName : string;    Address : string;    City : string;    State : string;    Zip : Integer;  end;</PRE><P>To create an include file, you simply start with a new text file and save it withan extension of INC. First, choose File | New from the main menu. Next, double-clickon the Text icon in the New Items dialog. A new text file will be created and openedin the Code Editor. Enter code and then save the file by choosing File | Save Asfrom the main menu. Be sure to give the file an INC extension or the file will besaved with a TXT extension by default.</P><P>To use an include file, you use the $I compiler directive in any other units thatneed to use the declarations in the include file. It looks like this:</P><P><PRE>unit Unit2;interfaceuses  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,    Dialogs,</PRE><P><B>StdCtrls;</B></P><P><PRE>{$I Test.inc}{ ... rest of unit follows }</PRE><P>The $I compiler directive tells the compiler to compile the contents of the includefile into the unit at that point. It's as if the include file were pasted into theunit at that point. You need to be sure that any code in the include file is syntacticallycorrect, or a compiler error will be generated. Don't be too concerned if this isa little confusing right now. It will probably take some experience writing realprograms for all this to come together for you.</P><P><H2><A NAME="Heading17"></A>Functions, Procedures, and Methods</H2><P>Functions and procedures are sections of code separate from the main program.These code sections are executed when needed to perform specific actions in a program.For example, you might have a function that takes two values, performs a complexmathematical calculation on those two values, and returns the result. You might needa function that takes a string, parses it, and returns a portion of the parsed string.You can call (use) these functions any time throughout your programs.</P><P>Functions and procedures can collectively be called <I>subroutines</I>. (Whilethe term subroutine is not commonly used in Pascal, it is a convenient word to coverboth functions and procedures, so I'll use it here.) Subroutines are an importantpart of any programming language, and Object Pascal is no exception. The simplesttype of subroutine takes no parameters and returns no value. Other subroutines mighttake one or more parameters and might return a value. Rules for naming functionsand procedures are the same as those discussed earlier for variables.</P><P><strong>New Term:</strong> A <I>function</I> is a section of code separate from the mainprogram that performs some action and returns a value.</P><P><strong>New Term:</strong> A <I>parameter</I> is a value passed to a function or procedurethat is used to alter its operation or indicate the extent of its operation.</P><P>Figure 2.2 shows the anatomy of a function.</P><P><A HREF="javascript:popUp('28670202.gif')"><B>FIGURE 2.2.</B></A><B> </B><I>Theanatomy of a function.</I></P><P><strong>New Term:</strong> A <I>procedure</I> is a section of code separate from themain program that performs some action but does not return a value.</P><P>Figure 2.3 shows the anatomy of a procedure.</P><P><strong>New Term:</strong> A <I>method</I> is a function or procedure that is a memberof a class.</P><P>As you can see from these descriptions, the only difference between a functionand a procedure is that a function returns a value and a procedure does not returna value.</P><P><A HREF="javascript:popUp('28670203.gif')"><B>FIGURE 2.3.</B></A><B> </B><I>Theanatomy of a procedure.</I></P><P>Let's write a program that uses a function. Once again, start with a new application.Then perform the following steps:</P><DL>	<DT></DT>	<DD><B>1. </B>Place a button component and a label component on the form.	<P>	<DT></DT>	<DD><B>2. </B>Double-click the button to create an OnClick event handler.	<P>	<DT></DT>	<DD><B>3. </B>Use the up-arrow key on the keyboard to move the editing cursor above	the event handler just created.	<P>	<DT></DT>	<DD><B>4. </B>Type the following function in the Code Editor:	<P></DL><BLOCKQUOTE>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -