C ++ primer Reading Notes-Chapter 7

Source: Internet
Author: User

Chapter 2 Functions

(I) Description and definition of functions
Variables are similar to variables:
(1) The function must be declared before calling
(2) function declaration can be separated from definition
(3) A function can be defined only once but can be declared multiple times.
The struct function declaration consists of the function return type, function return type, and form parameter list.
They describe the function interfaces, called function prototype)
(1) the operand of the function, that is, the parameter, which is declared in a pair of parentheses and separated by commas (,).
The parameter name is optional, but the parameter must be named when the function is defined.
(2) The operation executed by the function is defined in a block statement called the function body.
The struct function is generally declared in the header file and defined in the source file.
In this case, the latter should include the former so that the compiler checks whether the definition and declaration are consistent.
Handler specifies a small, frequently called functionInlineExpand the function at the call point to avoid additional overhead of calling the function.
But the inline description is only a suggestion for the compiler, And the compiler may choose to ignore it.

(Ii) function call and parameter transfer
Callback function call
(1) Use the call operator () to call a function.
① The operand is a real parameter (argument) separated by commas (,) between the function name and a group (which may be null)
② The result type is the type of the function return value, and the result is the function return value.
(2) function call:
① First (implicitly) define the form parameter and initialize it with the corresponding real parameter.
· The initialization of parameters is the same as that of variables:
If the parameter is not of the reference type, copy the value of the real parameter. If the parameter is of the reference type, it is only the alias of the real parameter.
② The execution of the calling function is suspended, and the called function is executed.
⒉ Non-reference parameter
(1) pointer Parameters
① The pointer can be passed in to indirectly access the object indicated by the pointer.
② If You Want To protect the object pointed to by the pointer, you can specify the parameter as pointingConstObject Pointer
(2)ConstParameters
① Used for initializationConstWhether it is a real parameter or not
ConstYes
The local copy of the real parameter cannot be changed in the function.
② Whether the non-reference parameter isConstDoes not affect the compiler's determination of the Function Type
· Note: differentiate pointers.ConstWhether to modify the nature of the pointer or the nature of the indicated object
(3) It is not suitable for copying real parameters.
① When you need to modify the real parameter value
② When large objects need to be passed as real parameters
③ When an object cannot be copied
You can solve the problem by defining the form parameter as a pointer or reference type.
References
(1) additional information can be returned using reference parameters.
(2) AvailableConstReference parameters to avoid copying real parameters
(3) Define reference parametersConstMore flexible
NonConstThe referenced parameter cannot be used.
ConstInitialize the Left or Right value, and define itConstNo problem
Usually, the worker transmits containers such as vector by passing the iterator.
Parameters array parameters
(1) When an array is directly passed as a real parameter to the function:
① If the form parameter is not an array reference, it is automatically converted to a pointer to the first element.
For example, the following three definitions are completely equivalent:
VoidF (Int*);
// Recommendation, explicitly specifying the operation object as a pointer
VoidF (Int[]);
VoidF (Int[10]); // The dimension is ignored by the compiler, which may cause misunderstanding.
② If the parameter is an array reference, no conversion will occur. The function obtains the array itself.
In this case, the compiler checks whether the dimension of the form parameter and the real parameter group match.
(2) When passing the array to the function for processing, you can:
The cursor uses the Standard Library Specification, that is, the first element pointer and the excess end pointer are passed in.
The first element address of the array is passed by the cursor, and the parameters representing the array size are passed explicitly.
(3) You can pass the pointer to the array to pass the ** Array
Functions with variable parameters
The features reserved to be compatible with the C language can only be passed into simple data types. Most class type objects cannot be copied correctly.
Default arguments
(1) By providing clear initial values for the parameters in the form parameter table, you can specify the default real parameters, as shown in
VoidF (
Int,Int=
1,Int=
2 );
① By default, real parameters can be any suitable expression.
② If a parameter has a default real parameter, all subsequent parameters must have a default real parameter.
③ In a file, the default real parameter can only be specified once for one form parameter
The default real parameter should be specified in the function declaration, and the declaration should be placed in the appropriate header file.
(2) real parameters with slight default values can be saved when a function is called: If omitted, the default real parameters are used; otherwise, the real parameters provided by the user are used.
· By default, real parameters can only be used to replace the real parameters missing by function calls.
Therefore, when designing a function with the default real parameters, you should first rank the parameters that use the default real parameters at least, and the parameters that use the default real parameters at most at the end.

(Iii) Scope and life cycle of local objects
The struct function is a scope. The variables defined in it are called local variables and can only be accessed in this function.
The local variables and parameters cannot be duplicated.
The automatically generated object (automatic objects) is a function-specific object. It is re-created each time the function is called and abolished at the end of the function.
Non-static local variables and parameters are both automatic objects.
BytesStaticMake sure that the local object is initialized no later than when the program executes the Definition Statement of the object for the first time. Once created, the local object will not be revoked before the end of the program.
When a function is called multiple times, the static local object will exist continuously and keep its value.

(Iv) return values andReturnStatement
The return type of the evaluate function can be a built-in type, a class type, or a composite type, but cannot be another function or a built-in array type.
IsVoidType indicates that this function does not return any value
BytesReturnStatement
Used to end the current function and return the control to the main function of the function.
(1) If no value is returnedReturnStatement
① It can be used only when the return type isVoidFunctions
② Optional, implicitReturnWhen the last statement of the function is completed
(2)ReturnStatement
① The return type is notVoidThe function must return a value (except the main function)
Note: It should be provided at the end of each execution path in the functionReturnStatement. If no compiler is provided, it cannot be found.
② Use the function return value to initialize the temporary object created at the called function, which is the same as the method for initializing the form parameter with the real Parameter
That is, if a non-reference type is returned, a copy is obtained. If a reference type is returned, the object itself is obtained.
③ Do not return references or pointers to local objects

(V) function Overloading
Contains two functions in the same scope. If they have the same name but different form parameters, they are overloaded functions)
Only those with different return types, different default real parameters, and non-reference parametersConstDifferent properties cannot be overloaded
If a function is declared locally, the function is blocked rather than overloaded with functions of the same name declared in the outer scope.
Three steps for determining the reload of a volume
(1) determine the set of candidate Functions
The candidate function is a function with the same name as the called function and can be declared on the call point.
(2) Select a viable function from the candidate function set (this call error is returned if no function is found)
Viable function meets two conditions:
① Function Form matches the number of real parameters involved in the call (considering the default real parameters)
② The type of each real parameter must match the corresponding parameter (the type is the same or can be implicitly converted)
(3) search for the best match (if multiple matches have the same degree, the call has ambiguity)
The principle is that the closer the real parameter type is to the shape parameter type, the better the matching result. The matching degree ranges from high to low:
① Exact match: The real participation parameters have the same type
② Matching Implemented through type improvement
③ Matching through standard conversion
④ Matching through class type conversion

(6) function pointer
Definition form
Return type (* identifier) (parameter table)
Regions availableTypedefSimplified definition
TypedefReturn type (* Custom type name) (parameter table)
Struct initializes and assigns values to function pointers. You can use:
(1) Functions of the same type
When a function name is referenced but not called, the function name is automatically interpreted as a pointer to the function.
Therefore, you can directly use the function name to initialize or assign values to the function pointer without using the address operator &
· Note: the pointer type must be exactly the same as the function type.
(2) function pointers of the same type
(3) constant expression with 0 values
Callback calls a function through a function pointer
You can directly use the function call operator () to call the specified function without using the unreferenced operator.
When the asterisk (*) function pointer is used as a parameter, the asterisk (*) can be written or not.
The pointer of the callback function is used as the return value of the function.
Function pointer return type (* function name (function parameter table) (function pointer parameter table)

(Vii) Main Function
Callback Return Value
(1) The main function return type isIntThe returned value is a status indicator in most systems.
If 0 is returned, the program runs successfully. If other values are returned, the program fails.
(2) Explicit use is not requiredReturnStatement. The Compiler implicitly inserts a statement that returns 0.
(3) to make the return value independent from the machine, the cstdlib header file defines two preprocessing Variables
Exit_failure (run failed) exit_success (run successful)
Using the main function parameters to process command line options
IntMain (IntArgc,
Char* Argv [])
· Argv is a C-style string array that stores the strings (including program names and parameters) entered when a program is called from the command line)
· Argc indicates the number of strings in argv
The main function of the handler is not allowed to be explicitly called, retrieved addresses, or overloaded.

Related Article

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.