tailieunhanh - Absolute C++ (4th Edition) part 15

Absolute C++ (4th Edition) part 15. KEY BENEFIT: C++ programming concepts and techniques are presented in a straightforward style using understandable language and code. KEY TOPICS: C++ Basics; Flow of Control; Function Basics; Parameters and Overloading; Arrays; Structures and Classes; Constructors; Operator Overloading, Friends, and References; Strings; Pointers and Dynamic Arrays; Separate Compilation and Namespaces; Streams and File I/O; Recursion; Inheritance; Polymorphism and Virtual Functions; Templates; Linked Data Structures; Exception Handling; Standard Template Library; Patterns and UML. MARKET: Useful for both beginning and intermediate C++ programmers. . | 142 Parameters and Overloading As shown in Display the definition of the function swapValues uses a local variable called temp. This local variable is needed. You might be tempted to think the function definition could be simplified to the following void swapValues int variablel int variable variable1 variable2 This does nOt Work variable variablel To see that this alternative definition cannot work consider what would happen with this definition and the function call swapValues firstNum secondNum The variables firstNum and secondNum would be substituted for the formal parameters variablel and variable so that with this incorrect function definition the function call would be equivalent to the following firstNum secondNum secondNum firstNum This code does not produce the desired result. The value of firstNum is set equal to the value of secondNum just as it should be. But then the value of secondNum is set equal to the changed value of firstNum which is now the original value of secondNum. Thus the value of secondNum is not changed at all. If this is unclear go through the steps with specific values for the variables firstNum and secondNum. What the function needs to do is save the original value of firstNum so that value is not lost. This is what the local variable temp in the correct function definition is used for. That correct definition is the one in Display . When that correct version is used and the function is called with the arguments firstNum and secondNum the function call is equivalent to the following code which works correctly temp firstNum firstNum secondNum secondNum temp CONSTANT REFERENCE PARAMETERS We place this subsection here for reference value. If you are reading this book in order you may as well skip this section. The topic is explained in more detail later in the book. If you place a const before a call-by-reference parameter s type you get a call-by-reference parameter that cannot be changed. For the types we have seen so far this

TỪ KHÓA LIÊN QUAN