C + + Primer 5th notes: Sixth chapter

Source: Internet
Author: User

Sixth chapter

Notes

1. Execute the function by calling the operator (call operator). The invocation operator is in the form of a pair of parentheses that acts on an expression that is a function or pointer to a function.

2. In the C + + language, the name has scope and the object has a life cycle.

A. The scope of the name is part of the program text and the name is visible in it.

B. The life cycle of an object is a period of time during which the object exists during program execution.

3. The function body is a block of statements that form a new scope.

4. The variables defined within the parameters and function bodies are collectively referred to as local variables (local variable).

5. A local static object is initialized when the program's execution path passes through the object definition statement for the first time, and is not destroyed until the program terminates.

6. A function can be defined only once, but may be declared more than once. The declaration of a function is also called a function prototype .

7. Each time the function is called, its formal parameters are recreated and the parameters are initialized with the passed-in arguments .

    8. in the C + + language, we recommend replacing pointers with formal parameters of reference types .

9. use references to avoid copying. Copying large class-type objects or container objects is inefficient, and even some class types (including IO types) do not support copy operations at all .

10. If the function does not need to change the value of the reference parameter, it is best to declare it as a constant reference .

//Bad design: The type of the first parameter should be const string&      string:: Size_type Find_char (string&s,CharC,string:: Size_type &occurs); //only the Find_char function can be applied to a string object. Find_char ("Hello World",'o', CTR);//Error//use constant references whenever possible

One. you can initialize an underlying cosnt object with very much, but not in turn.

12. The two special properties of an array are affected by the functions we define and use on the array: a. Copying arrays is not allowed; b. When you use an array, it is usually converted to a pointer.

The C + + language allows variables to be defined as references to arrays, and parameters can also be applied to an array.

// correct: The parameter is the application of the array, and the dimension is part of the type void print (int (&arr) [ten])   ///  &arr the brackets on both ends are necessary {     for (auto Elem:arr)       << elem << Endl; }        

14. Pass a multidimensional array. The size of the second dimension of the array is part of the array type and cannot be omitted .

//The matrix points to the first element of the array whose elements are arrays of 10 integers      voidPrintint(*matrix) [Ten],intRowsize) {/*  ...  */}//again, the brackets on both sides of the *matrix are essential//int *matrix[10]; Array of 10 pointers//Int (*matrix) [10]; Pointer to an array containing 10 integers//equivalence definition      voidPrintintmatrix[][Ten],intRowsize) {/*  ...  */}//The matrix declaration looks like a two-dimensional array, which is actually a pointer to an array containing 10 integers

Main: Handling Command-line options:

int Main (intChar *argv[])  //  second parameter argv is a one- dimensional array whose elements are the reference to the C-style string Pin      //  equivalence definition int main (intchar **argv)    {...}    

The new C + + standard provides two main methods: If all argument types are the same, you can pass a standard library type named Initializer_list. Unlike vectors, the elements in the Initializer_list object are always constant values , and we cannot change the values of the elements in the Initializer_list object.

The type of the return statement value must be the same as the return type of the function, or it can be implicitly converted to the return type of the function.

Returns a value in exactly the same way that a variable or parameter is initialized: The returned value is used to initialize a temporary amount of the call Point , which is the result of a function call .

do not return a reference or pointer to a local object .

//Critical Error: This function attempts to return a reference to a local object      Const string&Manip () {stringret; //change the RET in some way          if(!ret.empty ())returnRet//Error: Returning a reference to a local object         Else              return "Empty";//error: "Empty" is a local temporary quantity      }//the two return statements above will return undefined values, that is, attempting to use the return value of the Manip function to//undefined behavior occurs. For the first return statement, it is clear that it returns a reference to the local object. In the//in the second return statement, the string literal is converted to a local temporary string object, for Manip//the object is as local as the RET. When the function ends, the space occupied by the temporary object is freed,//A two return statement points to a memory space that is no longer available. 

A. reference returns an Lvalue . Calling a function that returns a reference gets an lvalue, and the other return type gets the right value.

//we can be a function of a very good reference for the return type      Char&get_val (string&AMP;STR,string:: Size_type ix) {returnStr[ix]; }intMain () {stringS"a value"); cout<< s << Endl;//output A valueGet_val (s),0) ='A';//change the value of s[0] to acout << S <<Endl; return 0; }//If the return type is a constant reference, we cannot assign a value to the result of the call

The new C + + standard specifies that a function can return a list of worthwhile braces surrounded by parentheses , similar to other return results, where the list is also used to indicate the initialization of the returned temporary amount .

vector<string>process () {//... ..//expected and actual are string objects          if(Expected.empty ())return {}; Else if(Expected = =Actual)return{"Functionx","Okay"}; Else        return{"Functionx", expected, actual}; }
If the function returns a class type, the class itself defines how the initialization value is defined

21. The trailing return type can be used in the c++11 new standard.

// Func takes an argument of type int and returns a pointer to an array of 10 integers , auto func (intint (*) [x];

22. Using Decltype

Note: Decltype is not responsible for converting the array type to the corresponding pointer, so the result of the Decltype is a set of arrays, and to return the pointer must also be added with a * symbol in the function declaration.

 int  odd[] = {1 , 3 , 5 , 7 , 9  };  int  even[] = {0 , 2 , 4 , 6 , 8  };  //  Returns a pointer to an array containing 5 integers  decltype (odd) *arrptr (int   i) { return  (i% 2 )?    &odd: &even; }

The function matching refers to a process in which we associate a function call with one of a set of overloaded functions, and function matching is also called function determination (overload resolution) .

once a parameter is given a default value, all parameters following it must have a default value .

25. When designing a function with default arguments, one of the tasks is to properly set the order of the formal parameters, try to make the parameters of the unused default values appear in front of them, and let those parameters that often use the default values appear behind.

26. Inline functions can avoid the overhead of function calls. Functions are specified as inline functions, usually by expanding them "inline" on each call point. In addition, the inline description is just a request to the compiler, and the compiler can choose to ignore the request.

27. Put the inline function and the constexpr function in the header file, after all, it is not enough for the compiler to expand the function only the declaration of functions, but also need the definition of the function.

28. Debugging help: Assert pre-processing macros. The so-called preprocessing macro is actually a preprocessing variable. The behavior of an assert depends on the state of a preprocessing variable named Ndebug. We can define ndebug using a # define statement, which turns off the debug state.

Summary of key points of knowledge:

    Function overloading:

      If several functions of the same scope have the same name but different parameter lists, we call this overloaded (overloaded) function .

I. Overloads and CONST parameters: the top-level const does not affect the incoming function object. A formal parameter with a top-level const cannot be distinguished from another parameter that has no top-level const:

Record Lookup (Phone); Record Lookup (const Phone);       //      The Record lookup (phone)  Record lookup (phone*) is repeatedly declared; Record lookup (Phoneconst);     // The Record lookup (phone*) was repeatedly declared

On the other hand, if a parameter is a pointer or reference of a certain type, it can be implemented by distinguishing whether it points to a constant object or a very heavy object, at which point the const is the underlying:

 //  for a function that accepts a reference or pointer, the object is a constant or a very variable corresponding parameter  //  defines 4 independent overloaded functions  Record lookup (            account&); //     function on account reference    Record lookup (const  account&); //  new function for constant reference            Record lookup (account  *); //     A new function for the pointer to account  Record lookup (const  account*); //  a new function for pointers to constants  

Analysis: In the example above, the compiler can infer which function should be called by whether the argument is a constant. Because const cannot be converted to other types, we can only pass a const object (or a pointer to a const) to the COSNT parameter. Conversely, because the very mass can be convertedto a const, the above four functions can be used for the very amount or pointer to a very good amount. However, when we pass a pointer to a very high-volume object or a very high-volume object, the compiler will prefer a very version of the function .

Two. Const_cast and overloading

Const_cast is most useful in scenarios where overloaded functions are available. For example:

//compares the length of two string objects to return a shorter reference      Const string&shorterstring (Const string&AMP;S1,Const string&S2) {returnS1.size () <= s2.size ()?s1:s2; }//The return result above is still a reference to the const STIRNG, so we need a new shorterstring function//, when its arguments are not constants, the result is a normal reference, which can be done using const_cast      string&shorterstring (string&AMP;S1,string&S2) {Auto&r = shorterstring (const_cast<Const string&>(S1), Const_cast<Const string&>(S2)); returnconst_cast<string&>(R); }//This reference is actually bound to an initial, very specific number of arguments, so we can convert it back to a//ordinary Stirng&--this is clearly safe.

Three. constexpr function

The CONSTEXPR function can only be used with a function of a constant expression. The return value type of the function and the type of all formal parameters are literal types, and there must be only one return statement in the body of the function.

Const        int NEW_SZ ()  return;  constint foo = NEW_SZ ();    // correct: Foo is a constant expression

The compiler replaces the call to the CONSTEXPR function with its result value.

Four. function matching (p217) (to be written)

Five. function pointer (p221) (to be written)

Terms

Invoke operator (call operator), automatic (Automatic object), local static object,

Function prototype, reference passing (passed by reference), value passing (passed by value),

Recursive loops (recursion loop), best match, preprocessing macros (preprocessor Marco), viable functions (viable function),

Ambiguity invocation (ambiguous call).

C + + Primer 5th notes: Sixth chapter

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.