📄 ch02.htm
字号:
<PRE>function Multiply(Num1, Num2 : Integer) : Integer;begin Result := Num1 * Num2;end;</PRE></BLOCKQUOTE><PRE></PRE><P><A HREF="javascript:popUp('28670204.gif')"><B>FIGURE 2.4.</B></A><B> </B><I>TheCode Editor showing the Multiply function.</I></P><P><PRE><I></I></PRE><DL> <DT><I></I></DT> <DD>Your Code Editor should now look similar to Figure 2.4. <P> <DT></DT> <DD><B>5. </B>Move back down to the OnClick event handler and type code until the event handler looks like this: <P></DL><BLOCKQUOTE> <PRE>procedure TForm1.Button1Click(Sender: TObject);var X : Integer;begin X := Multiply(10, 20); Label1.Caption := IntToStr(X);end;</PRE></BLOCKQUOTE><PRE></PRE><P>Run the program and click the button. The label will change to 200 when you clickthe button. Here's how it works: When you click the button, the Button1Click eventhandler is called. This, in turn, calls the Multiply function, passing the valuesof 10 and 20 as parameters. The result is stored in the variable X, which is thendisplayed in the label.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> This example illustrates the use of a standalone function in a Delphi program. I normally would have made this function part of the main form's class, but because we haven't talked about classes yet I would be getting ahead of myself by using that technique here. <HR></BLOCKQUOTE><P>You might be thinking, "Okay, but how does the product of the two numbersget back from the function?" Take another look at the Multiply function:</P><P><PRE>function Multiply(Num1, Num2 : Integer) : Integer;begin</PRE><P><B>Result := Num1 * Num2;</B></P><P><PRE>end;</PRE><P>Every Object Pascal function has a local variable called Result. This variableis declared invisibly by the compiler, and it is used to hold the return value fromthe function. To return a specific value from a function, then, is a simple matterof assigning that value to the Result variable within the function.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> There is another way of specifying the return value for a function. Rather than assigning the return value to the Result variable, you assign the return value to the function name. For example:</P> <PRE>function Multiply(Num1, Num2 : Integer) : Integer;begin Multiply := Num1 * Num2;end;</PRE></BLOCKQUOTE><PRE></PRE><BLOCKQUOTE> <P>You might see this method used in older Pascal programs or in programs ported to Delphi from Turbo Pascal (one of Delphi's predecessors). <HR></BLOCKQUOTE><P>The Multiply function can be called in one of several ways. You can pass variables,literal values, or even the results of other function calls. For example:</P><P><PRE>X := Multiply(2, 5); { passing literal values }X := Multiply(A, B); { passing variables }{ return value used as a parameter for another function }Label1.Caption := IntToStr(Multiply(X, Y)); Multiply(X, Y); { return value ignored }</PRE><P>Notice in the preceding example that the return value is not used. In this case,it doesn't make much sense to call the Multiply function and ignore the return value,but ignoring the return value is something that is done frequently in Object Pascalprogramming. There are many functions that perform a specific action and then returna value indicating the status of the function call. In some cases the return valueis not relevant to your program, so you can just ignore it. If you don't do anythingwith the return value, it is simply discarded and no harm is done.</P><P>Now let's add a procedure to the program by following these steps:</P><DL> <DT></DT> <DD><B>1. </B>Double-click the button on your form. The OnClick event handler is displayed just as you left it. <P> <DT></DT> <DD><B>2. </B>Move the editing cursor up a few lines so that it is between the Multiply function and the OnClick event handler. Type the following code: <P></DL><BLOCKQUOTE> <PRE>procedure SayHello;begin MessageDlg(`Hello There!', mtInformation, [mbOk], 0);end;</PRE></BLOCKQUOTE><PRE></PRE><DL> <DT></DT> <DD><B>3. </B>Move down a few lines and add one line of code to the end of the OnClick event handler so that it looks like this: <P></DL><BLOCKQUOTE> <PRE>procedure TForm1.Button1Click(Sender: TObject);var X : Integer;begin X := Multiply(10, 20); Label1.Caption := IntToStr(X); SayHello;end;</PRE></BLOCKQUOTE><PRE></PRE><P>Now run the program again. This time when you run the program, the result of theMultiply function is shown in the label as before, and then a message box appears.The message box is shown as a result of calling the SayHello procedure. Calling theSayHello procedure is extremely simple because the procedure takes no parameters.It's important to understand that the code in a function or procedure is executedonly if you specifically call the function or procedure from somewhere in your code.</P><BLOCKQUOTE> <P><HR><strong>TIP:</strong> Any time you find yourself repeating code more than a couple of times in your programs, think about moving that code to a subroutine. Then you can call the subroutine when you need to execute that code. <HR></BLOCKQUOTE><P>Subroutines can (and frequently do) call other subroutines. Subroutines can evencall themselves. This is called <I>recursion</I> and is one way to get into troublewhen programming! Recursion is best left alone until you've put in some time withthe Object Pascal language.</P><P><strong>New Term:</strong> <I>Recursion</I> is the process by which a procedure or functioncalls itself.</P><P><H3><A NAME="Heading18"></A>Declaration and Definition</H3><P>Functions and procedures often have a declaration and always have a definition.</P><P><strong>New Term:</strong> A <I>declaration</I> is a single statement that describesa method's name and parameters, if any. In the case of a function, the declarationalso indicates the function's return type.</P><P><strong>New Term:</strong> A function or procedure's <I>definition</I> is the actualbody of the function or procedure in the implementation section of the unit.</P><P>There are three primary cases where a declaration is necessary:</P><UL> <LI>When the function or procedure will be used by other units. <P> <LI>When the function or procedure definition falls below the place in the code where that function or procedure is called. <P> <LI>When the function or procedure is a member of a class.</UL><P>I haven't used declarations up to this point, only definitions. This is becausethe function definition always came before the place in the code where the functionwas actually used. Take the Multiply function, for example. If I had written a functiondeclaration for this function, it would look like this:</P><P><PRE>function Multiply(Num1, Num2 : Integer) : Integer;</PRE><PRE>As you can see, the function declaration simply describes the function. </PRE><P>Function and procedure declarations are placed in the interface section. Placinga declaration in the interface section automatically makes that function or procedureavailable to other units (makes it public, so to speak). If you don't want the functionor procedure to be visible to other units, you can't use a declaration. Instead,you will have to make sure that the function or procedure is defined near the topof the interface section so that it can be seen by all other methods in the unitthat use the function. As I said, the examples of functions and procedures up tothis point have used this method. I could have done it the other way and used bothdeclaration and definition. Here's part of a unit that contains a declaration forthe Multiply function, a Button1Click method that calls the Multiply function, andthe definition of the Multiply function:</P><P><PRE>unit Unit1;interface{ some code removed... }function Multiply(Num1, Num2 : Integer) : Integer;implementationprocedure TForm1.Button1Click(Sender: TObject);var X : Integer;begin X := Multiply(10, 20);end;function Multiply(Num1, Num2 : Integer) : Integer;begin Result := Num1 * Num2;end;end.</PRE><P>In this case the declaration is necessary because the Multiply function is defined<I>after</I> the Button1Click method that calls it. The declaration tells the compilerthat a function can be found later in the unit. You'll learn more about functiondeclarations tomorrow when we talk about methods in classes.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> If you declare a function but neglect to define it, the compiler will issue an error that says, Unsatisfied forward or external declaration: `Multiply.' <HR></BLOCKQUOTE><P><H3><A NAME="Heading19"></A>Value, Constant, and Reference Parameters</H3><P>Parameters to functions or procedures can be of at least three different types(more than three, actually, but I'll only discuss three types here).</P><P><H4>Value Parameters</H4><P>First, parameters can be <I>value parameters</I>. All the parameters you haveseen up to this point have been value parameters. The value parameter acts like alocal variable in the function or procedure. You can modify the variable within thefunction and the original variable will remain unchanged. Let's create a new functionthat illustrates the point. This function will be called SquareAndMultiply. It willtake two numbers, square them, multiply them together, and return the result. Hereit is:</P><P><PRE>function SquareAndMultiply(Num1, Num2 : Integer) : Integer;begin Num1 := Num1 * Num1; Num2 := Num2 * Num2; Result := Num1 * Num2;end;</PRE><P>Now let's look at the code that will call this function:</P><P><PRE>procedure TForm1.Button1Click(Sender: TObject);var X : Integer; Y : Integer; Z : Integer;begin X := 2; Y := 3; Z := SquareAndMultiply(X, Y); Label1.Caption := IntToStr(Z);end;</PRE><P>If you want, you can enter this code to test it out. Two values are passed toSquareAndMultiply. The two values are modified inside the SquareAndMultiply functionbecause the numbers need to be squared before they are multiplied together. However,the original values of X and Y in the Button1Click method do not change. When a functionuses a value parameter, the compiler first makes a copy of the variable passed tothe function and then sends the copy to the function. The original variable is unchangedbecause the copy is sent to the function and not the actual variable.</P><P><H4>Constant Parameters</H4><P>Another way to send values to functions is to use <I>constant parameters.</I>A constant parameter cannot be changed inside the function body. Here's an exampleof a procedure that takes a constant parameter:</P><P><PRE>procedure SaySomething(const S : string);begin S := S + `Test'; ShowMessage(S);end;</PRE><PRE>This is one of the few code examples in this book that contains an error (I hope!). The compiler will issue an error on the first line in this procedure. The compiler error will say, Left side cannot be assigned to. The error is generated because the const keyword stipulates that the variable S cannot be modified. Any attempts to modify the constant parameter will result in a compiler error. Write procedures and functions using constant parameters when you don't want the passed variable to be modified within the function. </PRE><H4>Reference Parameters</H4><P>A third way to send values to functions is to use <I>reference parameters</I>.When you use a reference parameter, the compiler does not make a copy of the objectas it does when using value parameters. Rather, the actual variable is passed. Thismeans that any changes made to the variable in the function or procedure will modifythe original variable. The following is an example of a procedure that uses a referenceparameter (both the procedure and the use of the procedure are shown):</P><P><PRE>procedure Square(var Number : Integer);begin Number := Number * Number;end;procedure TForm1.Button1Click(Sender: TObject);var X : Integer;begin X := 20; Square(X); Label1.Caption := IntToStr(X);end;</PRE><P>First look at the Square procedure. Notice that the variable parameter is designatedby using the var keyword. Because the var keyword is used to declare reference parameters,those parameters are commonly called <I>var parameters.</I> I'll use the terms interchangeablyin this section.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> Many Object Pascal keywords do double duty. In this case, the var keyword is used to declare a reference parameter. Previously you have seen the var keyword used to declare variables in a function, procedure, or unit. The compiler knows the context in which the keyword is being used and therefore knows how
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -