7.1 Definition of function
A function call does two things: Initialize the formal parameters of the function with the corresponding arguments, and transfer the control to the tuned function.
Return the greatest common divisor int gcd (int v1, int v2) {while (v2) {int temp = v2; V2 = v1% V2; V1 = temp; } return v1; }
7.2 Parameter Passing
The initialization of the formal parameter is the same as the initialization of the variable, if the parameter has a non-reference type, the value of the argument is copied, and if the parameter is a reference type, it is only the alias of the argument.
Non-reference formal parameters
The argument replica initial taxiing parameter, the function does not access the argument itself, and therefore does not modify the value of the argument.
1) pointer parameters
To protect the value pointed to by the pointer, the formal parameter must be defined as a pointer to a const object;
2) Const formal parameter
If the formal parameter is a normal parameter, the const argument can be passed because the initialized value is copied.
If the parameter is a const parameter, the local copy of the argument cannot be changed in the function.
What are surprising, is and although the parameter is a const inside the function,//the compiler otherwise treats T He definition of FCN as if we had defined the parameter as a plain int:void FCN (const int i) {/* FCN can read but not WRI Te to I/*}void FCN (int i) {/* ... */}//Error:redefines FCN (int)
3) It is not appropriate to copy the actual parameters
You need to modify the argument value; A large object is passed as an argument; Cannot implement object replication
Reference formal parameters
A reference parameter is directly associated with the object to which it is bound, not a copy of those objects.
1) Reference Parameters return additional information
Returns an iterator, refers to the first occurrence of value//the reference parameter occurs contains a second RET Urn Valuevector<int>::const_iterator find_val ( vector<int>::const_iterator Beg,//First element Vector<int>::const_iterator End,//one past last element int value,//The value we want vector<int >::size_type &occurs)//number of times it occurs{ //Res_iter'll hold first occurrence, if any vector&l T;int>::const_iterator res_iter = end; Occurs = 0; Set occurrence count parameter for (; Beg! = end; ++beg) if (*beg = = value) { //Remember first occurrence of value if (res_iter = = end) res_iter = Beg; ++occurs; Increment occurrence Count } return res_iter;//count returned implicitly in occurs}
2) Avoid replication with const references
To avoid copying the arguments and not modifying the arguments, you should define the formal parameters as const references.
Reference parameters that do not need to be modified should be defined as const references. Ordinary non-const reference parameters are not very flexible to use. Such a parameter cannot be initialized with a const object, or by an expression argument that produces an rvalue or a literal value.
Parameters for vectors and other container types
From the point of view of avoiding copying vectors, consider declaring a parameter as a reference type. In fact, C + + tends to pass containers by passing iterators that point to elements in the container.
Pass iterators to the first and one past the last element to printvoid print (Vector<int>::const_iterator beg,
vector<int>::const_iterator end) { while (beg! = end) { cout << *beg++; if (beg! = end) cout << ""; No space after last element } cout << Endl;}
Array formal parameters
Two special properties of the array: 1) cannot copy the array directly; 2) when using an array name, the array name is automatically converted to a pointer to its first element.
Specifying an array parameter
Three equivalent definitions of printvaluesvoid printvalues (int*) {/* ... */}void printvalues (int[]) {/* ... */}voi D printvalues (int[10]) {/* ... */}
The length of the array is not checked when the compiler checks the arguments associated with an array parameter.
Passing Arrays by reference
An array parameter can declare a reference to a group. If the parameter is a reference to an array, the compiler does not convert the argument to a pointer, but instead passes the array's reference itself. The compiler checks that the array argument size and parameter size are consistent.
Other
Any program that handles arrays ensures that the program stays within the bounds of the array.
Main: command-line processing options
int main (int argc, char *argv[]) {}
The first string of argv is the program name, and the arguments passed to the main function start with the argv[1]
Functions containing deformable parameters
void foo (parm_list, ...); void foo (...);
7.3 Return Statementfunction with return value
It is dangerous not to provide a return statement after a loop that contains a return statement, because most compilers cannot detect the vulnerability, and what happens at run time is uncertain.
Return non-reference type
When the return type is not a reference, the function return value is copied to the temporary object where the function is called. The return value can be either a local object or a result of solving an expression.
China
You must never return a reference to a local variable. When the function finishes executing, the storage space allocated to the local object is freed. At this point, the reference to the local object points to the indeterminate memory.
You must never return a pointer to a local object.
Recursive
Recursive version greatest common divisor programint rgcd (int v1, int v2) { if (v2! = 0)//we ' re done once v2 gets To zero return RGCD (v2, V1%V2);//recurse, reducing v2 on each call return v1;}
7.4 function Declarations
A function declaration consists of a return type, a function name, and a formal parameter list, which are referred to as functions prototype, and the parameter names in function declarations are ignored.
Default actual parameters
A default argument can is any expression of an appropriate type:
String::size_type screenheight (); String::size_type screenwidth (String::size_type); char screendefault (char = "); String Screeninit ( string::size_type height = screenheight (), string::size_type width = screenwidth ( ScreenHeight ()), char background = Screendefault ());
In a file, you can specify a default argument only once for one parameter. The default argument should be specified in the function declaration. If you provide a default argument in the formal parameter list of a function definition, the default argument is valid only if the function is called in the source file that contains the function definition.
7.5 Local Objects
The scope of a name refers to the area of the program text that knows the name, and the object's lifetime refers to the time at which the object existed during the execution of the program.
Automatic objects
By default, the lifetime of a local variable is limited to the duration of each execution of the function. An object that exists only when the function that defines it is invoked is called an automatic object. Automatic objects are created and revoked each time the function is called.
Static local objects
A variable is located in the function scope, but life spans multiple invocations of the function, which should be defined as static.
The static local object is guaranteed to be initialized no later than the first time the program execution process passes through the object's definition statement. Once created, this object will not be revoked until the end of the program.
7.6 Inline Functions
Background: Calling a function is much slower than solving an equivalent expression
Call function to do a lot of work, 1) to save the register before the call, and restore on return, 2) Copy the arguments, 3) The program must also go to a new location to execute.
inline function (inline) avoids the overhead of calling a function
Specifying a function as an inline function expands it "inline" on each call point in the program. Inline instructions are only a recommendation for the compiler.
Inline functions are defined in the header file
The definition of an inline function must be visible to the compiler so that the compiler can expand the code of the function within the calling point. At this point, only the function prototype is not enough.
member functions for class 7.7member functions
The compiler implicitly considers the member functions defined within the class as inline functions;
When a non-static member function is called, the implicit parameter of this is initialized to the address of the object that called the function .
The const member function in const changes the type of the This parameter so that this becomes a pointer to a const object, and therefore cannot modify the data member of the object.
A const object, a pointer to a const object, or a reference can only be used to invoke its const member function.
constructor function
The default constructor describes what to do when defining an object without explicitly initializing it
Constructor is a public member
We want to use the code of the class to define and initialize the object of the class, and if the constructor is defined as private, you cannot define the object of the class. (Only members defined in the public section can be accessed using all code of that type)
the default constructor for a composition
If no constructors are defined for a class display, the compiler will automatically generate a default constructor for this class, that is, synthesized default constructor, which initializes all members of the class based on the variable initialization rules.
Synthetic default constructors generally apply to classes that contain only class-type members . For classes that contain members of built-in or composite types, you should typically define their own default constructors to initialize those members.
7.8 overloaded FunctionsSome concepts of overloading
Precise definition
Functions in the same scope, with the same name and a different formal parameter list.
Differences from duplicate declarations
The parameter lists can be identical, even if they don ' t look the same:
Each pair declares the same Functionrecord lookup (const account &ACCT); Record lookup (const account&); Parameter names is ignoredtypedef Phone Telno; Record lookup (const phone&); Record lookup (const telno&); Telno and Phone is the same Typerecord lookup (const phone&, const name&);//default argument doesn ' t change th E Number of Parametersrecord lookup (const phone&, const name& = "");//const is irrelevent for Nonreference parame Tersrecord lookup (Phone); Record lookup (const Phone); Redeclaration
Copying a parameter does not take into account whether the formal parameter is const, the function manipulates only the copy, and the function cannot modify the argument. When a parameter is passed as a copy, it cannot be overloaded based on whether the formal parameter is const
Argument type conversions
1) Match of type promotion or conversion
Smaller integral type promoted to int type
void ff (int); void ff (short); FF (' a '); char promotes to int, so matches f (int)
Conversions implemented by type promotion are better than other standard conversions, such as char to int better than Double,char to double than unsigned char
2) parameter matching and enumeration type
When an enumeration value is passed to an integer parameter, the enumeration value is promoted to an int or a larger integer type.
3) overloads and const parameters
The parameter is const only if the parameter is a reference or a pointer.
7.9 pointers to functions
A function that points to a pointer is called a function pointer, and the function pointer points to a specific type, which is determined by its return type and formal parameter list, regardless of the function name.
Simplify function pointer definition with typedef
typedef BOOL (*CMPFCN) (const string &, const string &);
function name and function pointer
The direct reference function name is equivalent to applying the FETCH address operator on the function name;
function pointers can only be initialized and assigned by a function or function pointer of the same type or by a 0-value constant expression;
There is no conversion between pointers pointing to different function types;
Calling functions with pointers
CMPFCN PF = lengthcompare;lengthcompare ("Hi", "Bye"); Direct CALLPF ("Hi", "Bye"); Equivalent call:pf1 implicitly dereferenced (*PF) ("Hi", "Bye"); Equivalent CALL:PF1 explicitly dereferenced
A function's formal parameter can be a pointer to a function
/* Usebigger function ' s third parameter is a pointer to function* that function returns a bool and takes both const string references* ways to specify, parameter:*///third parameter is a function type and is automatically treated as a P Ointer tofunctionvoid Usebigger (const string &, const string &, bool (const string &, const string &)); Equivalent declaration:explicitly define the parameter as a pointer to functionvoid Usebigger (const string &, cons T string &, bool (*) (const string &, const string &));
A parameter is allowed to be defined as a function type (real arguments is automatically converted to a function pointer), but the return type of the function must be a pointer to a function, not a function.
Func is a function type, not a pointer to Function!typedef int func (int*, int); void F1 (func); OK:F1 has a parameter of function Typefunc f2 (int); ERROR:F2 has a return type of function Typefunc *f3 (int); OK:F3 returns a pointer to function Typ
pointers to overloaded functions
In the C + + language, when a function pointer points to an overloaded function, the type of the pointer must exactly match one version of the overloaded function.
[C++primer] [07] Function