Although, there is a certain C + + foundation (because the undergraduate has learned this kind, haha), but still decided to read the system of the book (before a few times before. Sweat).
Leave it for your own reference later. (The content will be changed irregularly, keep learning (this should be a long tone ~ ~))
Most of them are not solid enough to grasp the place and some of the details that have not been noticed before.
Many places in the book, detailing the cause of the emergence of knowledge, at the very least, to solve what problems arise!!
Foreword part
1. "... Extensive use of front and back cross-references ... "(very suitable for their own, I want to know how the original, I hope to have the opportunity to add to the original time ~)
2. The author's position on the book is this guide reading ...
3. The author assumes that the reader has mastered a modern structured language!
4. Learn enough knowledge to create your own abstraction (in the third to the fifth part of the discussion)
Quick Start Section
1. ' The operating system uses the value returned by the main function to determine whether the program completed successfully. ’
2.IDE (Integrated development environment) integrated development environment (not introduced in the book)
3. Note Comment
4. Enter the integer input for unknown purpose (using the input operator >> return to its left operand)
#include "stdafx.h" #include <iostream>using namespace Std;int main () {int sum=0,value;while (cin>>value) Sum+=value;cout<<sum<<endl;return 0;}
for the end of the input, see reading the Unknown object input (input non-integer end)
Variables and basic types
1. Basic character Set (char)
Extended Character Set (wchar_t)
2. Integral type (integral type): Collectively representing the arithmetic types of integers, characters, and Booleans
3. Literal rules
0240x14
20L 20UL 20FL (F single precision)
Scientific counting Method
string literal: In order to be compatible with C, all string literals in C + + are automatically appended by the compiler to a null character at the end. (type: An array of const char types)
4. Escape character \***
5. Initialize (create variable and assign value) assignment (erase the object's current value and replace it with the new value)
int a = 10;copy-initialization more flexible and more efficient
int a (ten); direct-initialization
6. The constructor (constructor) defines how the member functions are initialized. (Can have multiple)
PS: (P43 the second section of the last sentence a little flaw, it can be understood) there are multiple initialization parameters when you cannot use replication initialization.
7. Definition is used to allocate storage space for a variable, and you can also specify an initial value for the variable.
The Declaration (Declaration) is used to indicate to the program the type and name of the variable extern
int i;//declares and defines iextern int i;//declares but does not define Iextern int i = 1;//definition
8.the non-const variable defaults to extern. The const variable defaults to a local variable that defines the variable's file.
int i;//global variable const int i = local variable of 1;//file extern const int i = 1;//const must be initialized when defined
(The const variable defaults to a local variable for the file that defines the variable.) ) Why? allows the const variable to be defined in the header file. See
The const variable must be initialized when it is defined! (Use definition only once, to achieve the purpose that cannot be modified)
You can initialize a non-const object with a const object, and vice versa. Initialized values are copied because of initialization.
9. A reference (reference) is another name for the object it binds to. The reference returns the left value. Used primarily as a form parameter of a function.
A reference must be initialized, and initializer must is an object.
When a reference is initialized, it remains bound to the object pointed to when the reference exists. It is not possible to bind a reference to another object.
Composite type (compound type is defined with other types) (note: References to reference types cannot be defined)
10.typedef can be used to define synonyms for a type
One of the purposes of a typedef: When a type is used for multiple purposes, the purpose of each use of that type is clear.
PS: Part of the translation of this book is indeed not very accurate, although I have not read the original, but the feeling is jiangzi.
11. Enumeration enumeration: Resolves the associated problem with numeric values.
Enumeration member values can be non-unique.
Each enum defines a unique type. The initialization or assignment of an object of an enumerated type can only be done through its enumeration members or other objects of the same enumeration type!
The only difference between the 12.class and the struct keyword definition classes is the default access level: By default, the members of a struct are private public;class.
13. Header file should not contain definitions!
Three exceptions: the class, the const object (the value is known at compile time), and the inline function.
Cause: The compiler needs to know their definition to generate code.
When a const object is defined in a header file, it must be a const object initialized with a constant expression! PS: Subsequent chapters-const object definition in header file (to be perfected)
Part of the #include设施是C + + preprocessor (preprocessor).
#include指示只接受一个参数: Header file name. The preprocessor replaces each # include with the contents of the specified header file.
15. header File Protector (header Guard) to avoid re-processing the contents of the header file if it has already been seen. (The actual is to prevent multiple definitions)
The preprocessor indicates #ifndef #define #endif
Preprocessor variables: There are two states (defined and undefined). You cannot use a preprocessor variable to give a custom variable a name (such as A=null//error).
Standard library Type
1. Abstract data Type ADT
2. The header file should only define what is really necessary.
Use a fully qualified standard library name, that is, no using declaration. (Because the program that contains the header file also has this using declaration, regardless of whether it is required)
3. String literals are not of the same type as the standard library string type.
4. Read into the unknown destination string object
<pre name= "code" class= "HTML" >string Word;//read until end-of-file, writing each word to a new Linewhile (CIN >> ; Word) {cout <<word<<endl;}
5. Read into the unknown destination line
6. Do not assign the value of the return value of the size operation of string to an int variable! ( its return value is: String::size_type type , does not return int type to machine-independent)
The safest way to save a string object size is to use the standard library type String::size_type.
The index variable of a string object is best also used with the String::size_type type.
7. The standard library type is designed to be as easy to use as the basic data type.
Assignment operation for 8.string library type: Release the original memory, allocate new memory, copy.
The 9.C standard library header file is named Name.h, while the C + + version of this header file is named CNAME (c indicates that the header originated from the C standard library). Examples Cctype and ctype.h
Typically, C + + programs should use the version of the header file for the CNAME.
10.vector Object Dynamic Growth
The size of the 11.vector object that returns the value of the size_type defined by the corresponding vector class.
Vector<int>::size_type //okvector::size_type //error
12. Adding elements to vectors
String word;vector<string> text;while (cin>>word) {<span style= "White-space:pre" ></span> Text.push_back (word);}
13.c++ programmers are accustomed to using! = rather than < to write loop-judging conditions. (Generic programming)
14. An iterator (iterator) is a data type that examines the elements within a container and traverses the elements.
Modern C + + programs tend to use iterators rather than subscript operations to access container elements.
Iterators (iterator) and iterator types (example Vector<int>::iterator)
The iterator returned by the end operation points to the next "end element of the vector" (Off-the-end iterator). It's just a Sentinel (Sentinel) that says we've done all the elements in the vector.
The dereference operator (* operator) *iter = 0;
Const_iterator
Any action that alters the length of the vector will invalidate an existing iterator.
15. Initialize the Bitset object with a String object (the order in which the bit sets are read from a string object is right-to-left!) )
Arrays and pointers
1. Well-designed programs use arrays and pointers within the class implementation only when the speed is stressed.
2. Array disadvantage: fixed length; no size operation; direct copy and assignment not allowed
But it's still going to be ~ ~
3. The correct type of array subscript: size_t
4. Buffer Overflow (overflow)
5. When you understand pointer declaration statements, read from right to left.
6. If the pointer and the object it points to must be defined separately, the pointer is initialized to 0. (null equivalent to 0, is a preprocessing variable inherited from C, in the Cstdlib header file)
7.void* pointer Surface this pointer is associated with an address, but it is unclear what type of object is stored on this address. only limited operations are supported:
Compare with another pointer;
Passing a void* pointer to a function or returning a void* pointer from a function;
Assigns a value to another void* pointer.
8. Comparison of pointers and references
References always point to an object: the reference must be initialized when it is defined (the reference will always point to the same particular object once it is initialized).
Difference in assignment behavior: A reference assignment modifies the value of the object to which the reference is associated.
9. The result of the two pointer subtraction operation is the data for the standard library type ptrdiff_t. defined in the Cstddef header file.
10. As long as the pointer is pointing to an array, it can be subscript.
int *p = &ia[2];int J = P[0];int k = p[-2];
11. A pointer to a const object (understood as "a pointer to a const"), commonly used as a function's formal parameter (to ensure that the actual object passed to the function is not modified in the function because of the parameter)
You can initialize a pointer to a const object to point to a non-const object, but you can not point a pointer to a non-const object to a const object.
read about some of the issues generated by the Const declaration statement, since the Const qualifier can be placed before the type or after the type
Example: Pointers and typedef
typedef string *pstring;//all Three Decreations is the same type.they is all const pointers to String.const pstring CStr 1;string *const cstr2;pstring const CSTR3;
13.C style strings (C-style character string) cannot be attributed to the type of C language, nor to the C + + language type.
instead, an array of characters ending with null characters。
C + + manipulates C-style strings with a pointer to the (const) char* type. (if there is no null end ...) )
const char *CP = "some value"; while (*CP) {<span style= ' white-space:pre ' ></span>//do something to *cp<span Style= "White-space:pre" ></span>cp++;}
Never forget the string terminator null
14. Free Store or heap: Each program consumes a single piece of available memory space to hold dynamically allocated objects at execution time.
C Language: malloc and free
C + + language: New and delete
15. Dynamic arrays
Initializes an array of elements using a pair of empty parentheses following the length of the arrays.
int *pia = new Int[10];<span style= "White-space:pre" ></span>//array of ten uninitialized intsint *pia2 = new in T[10] (); <span style= "White-space:pre" ></span>//array of ten int value-initialized to 0
Calling new to create an array of length 0 is legal (but cannot be dereferenced)
Char arr[0];<span style= "White-space:pre" ></span>//error:can not define zero-length arrarychar *CP = new Char[0];<span style= "White-space:pre" ></span>//ok:but CP can not be dereferenced
The release of dynamic space (memory leak leak) delete[]
16. String objects can be initialized or assigned using a C-style string.
You need to use C_STR () to implement a string object's initialization or assignment of a C-style string.
const char *STR = ST2.C_STR ();
17. Pointers to multidimensional arrays
int *ip[4];//array of pointers to Intint (*p) [4];//pointer to an array of 4 ints
To simplify pointers to multidimensional arrays with typedef
An expression
1.c++ provides a rich number of operators and defines the meaning of these operators when operands are built-in types. (The meaning of the operator operator, depending on the type of the operand operand)
Unary operator, binary operator, ternary operator
To understand an expression consisting of multiple operators, you must first understand the precedence of the operators (precedence), associativity (associativity), and the Order of Evaluation of the operands (Order of evaluation).
Precedence: Examples of low-priority applications
int I;while ((i = Get_value ())! =) { //get_value () returns an int//do something}
Associativity: (Example: Left-associative cin>>a>>b right-associative int a=b=0)
The operator in order of evaluation:c++ that specifies the sequence of operands is the &&, | |, comma operator, and condition operator. Example See 3 short-circuit evaluation
2. Operator% (Remainder/modulus) Two operands are positive, negative negative, positive or negative, minus positive results. (the latter two depend on the machine)
3. Short-circuit evaluation (short-circuit evaluation): the logical and logical OR operator always calculates its left operand first, and then computes its right-hand operand. The right operand is solved only if the value of the left-hand operand cannot determine the result of the expression.
4. For bitwise operators, it is strongly recommended to use the unsigned integer operand because the system does not guarantee how to handle the sign bits of its operands.
<< 0,>> based on specific
5. Compound assignment operator (the left operand is evaluated only once, and two times when a similar long expression is used)
6. Use the post operator only if necessary. (because the predecessor operation requires less work)
7. The arrow operator, C + +, is a synonym for the definition of the dereference operation that is used after the dot operator.
8.sizeof a little explanation, pay attention to understanding.
Applying sizeof to the expression expr will get the type length of the result of the expression, but the value of the expression expr is not evaluated!
(especially in sizeof *p, the pointer p can hold an invalid address because the p does not need to be dereferenced.) )
9. Comma operator: The result is the value of its rightmost expression, often used for a for loop.
10. Type conversion: implicit type conversion (implicit type conversion), arithmetic conversion (arithmetic conversion), explicit conversion (forced type cast cast)
1) When an implicit type conversion occurs
A mixed-type expression, a conditional expression is converted to a bool type, a variable is initialized with an expression (or an assignment), and a function call.
2) Forced type conversion (static_cast, dynamic_cast, Const_cast, reinterpret_cast) (avoid using as much as possible)
Legacy Coercion Type conversions
Type (expr);//function-style cast notation (type) Expr;//c-language-style cast notation
Statement
1. When using an empty statement, a comment should be added so that anyone reading this code knows that the statement was intentionally omitted.
2. Compound statements (compound statement), commonly referred to as blocks, are sequences of statements enclosed in a pair of curly braces.
A compound statement is a place where a syntax rule requires that a single statement be used, but the program logic requires more than one statement. Compound statement, (example: loop body of a looping statement) is syntactically a single statement
3. Whether a class type can be used in a conditional expression depends on the class itself. (IO type Yes)
The 4.switch statement provides a more convenient way to implement deep nesting of if/else logic.
The execution flow of the case label starts at that point and continues executing other statements across the case boundary until the switch finishes or the break statement is encountered. (You should provide some explanatory notes when you deliberately omit the break statement that follows the case)
The default label provides functionality equivalent to the ELSE clause. (the default label is defined to tell its readers that the surface has been taken into account)
To avoid the occurrence of code skipping the definition and initialization of a variable, a switch structure can only be defined after its last case label or the default label (scope is the entire switch) variable. Block statement exception.
The 5.do while statement always ends with a semicolon.
The 6.break statement is used to end the most recent while, do, and for or switch statements, and to pass the execution of the program to the statement immediately following the terminated statement.
The 7.continue statement causes the current iteration of the most recent loop statement to end prematurely. Can only appear in a for, while, or do While loop.
8.throw expressions, try Blocks (try block), catch clauses (catch clause)/processing code (handler), Exception classes (Exception Class)
The process of looking for code is just the opposite of a function call chain. (Balabala)
9. Debugging with a preprocessor
Thought: The debug code contained in the program is only executed during development. When the application is complete and ready to commit, the debug code is closed.
int main () {#ifndef ndebugcerr<< "starting main" <<endl; #endif//...
Use Ndebug preprocessing variables and assert preprocessing macros for debugging.
Unlike exceptions, which are used to handle errors expected to occur when the program executes, the programmer uses assert to test for "impossible" conditions.
Function
Formal parameter (parameter), calling operator (call operator is a pair of parentheses), argument (argument)
1. Function call (two things done): Initializes the function's formal parameter with the corresponding argument, and transfers control to the called function. The execution of the calling function is suspended, and the called function begins execution.
2. In the C language, there is no difference between a function with a const parameter or a non-const parameter. C + + in order to be compatible, so 、、、
3. Limitations of duplicate arguments. Workaround: Define the parameter as a reference or pointer type. (Programmers who go from the C-language background to C + + are accustomed to passing pointers for access to the arguments.) In C + +, using reference parameters is more secure and more natural.
4. Non-const parameter: Avoid copying arguments, and use reference parameters to return additional information (also can be returned by an additional reference parameter).
Const parameter: Avoids copying arguments and prevents the corresponding arguments from being modified.
reference parameters that do not need to be modified should be defined as const references. Ordinary non-const reference parameters are less flexible to use: they cannot be initialized with a const object, or they cannot be initialized with literal values or an expression argument that produces an rvalue.
5. Passing a reference pointing to a pointer
The definition of void ptrswap (int *&v1, int *&v2) { //int *&v1 should be understood from right to left: V1 is a reference, associated with a pointer to an int type object. int *tmp = V2;v2 = V1;VI = tmp;}
Swaps the pointer to an object, instead of the object that the pointer is pointing to ~ (improves performance?). Just some time, right? )
6.c++ is more inclined to pass containers by passing iterators that point to the elements in the container that need to be processed.
7. Array parameters, the compiler ignores the length specified by any array parameter.
By passing an array by reference, the size of the array becomes part of the form parameter and the argument type, and the compiler checks that the size of the array arguments matches the size of the parameter.
f (int (&arr) [])//arr is a reference to an array of ten INTSF (int &arr[10])//arr is an array of references
8. Delivery of multidimensional arrays: The compiler ignores the length of the first dimension.
void printvalues (int matrix[][10], int rowsize)
9. Any program that handles arrays ensures that the program stays within the bounds of the array. There are three common programming techniques:
1) Place a tag in the array itself to detect the end of the array. (for example, C-style strings)
2) pass a pointer to the next position of the first and last element of the array. (Technology in the standard library)
3) define the second parameter as a representation of the size of the array. This usage is common in C programs and pre-standardized C + + programs.
10. Ellipsis parameter: The type check mechanism is paused.
11.return statements
function with no return value: return; (or implicit)
function with return value: return expression;
It is dangerous to not provide a return statement after a loop that contains a return statement, because most compilers cannot detect the vulnerability.
Never return a reference or pointer to a local object!
12. Function prototype (functions prototype) = function return value + function name + formal parameter list
13. Default argument: You can specify a default argument either in a function declaration or in a function definition. However, in a file, you can specify only one default argument at a time.
In general, you should specify the default argument in the function declaration and place the declaration in the appropriate header file. (also: The default argument is valid only if the file contains a default argument)
14. Automatic objects (automatic object), static local objects (static locally object)
size_t Count_calls () {<span style= "white-space:pre" ></span>static size_t ctr = 0;<span style= " White-space:pre "></span>return ++ctr;}
15. Inline functions avoid the overhead of function calls (calling a function is much slower than solving an equivalent expression).
Specifying a function as an inline function means that it expands "inline" on each invocation point in the program.
The inline mechanism is useful for optimizing small, only a few lines of functions that are often called.
Inline functions should be defined in the header file!
16. member functions of the class: the this pointer, constant member functions (const member function), constructors (constructor)
This pointer, each member function (except for the static member function) has an additional, implicit formal parameter of this.
Constant member function (const member functions), const this pointer
Initializer list of constructors (constructor initializer lists)
The synthesized default constructor (synthesized-constructor) does not automatically initialize members of built-in types ! Generally applies to classes that contain only class-type members.
17. Overloaded functions (overloaded function): appears in the same scope, has the same name, the formal parameter list is different
The difference between function overloads (functions overloading) and duplicate declarations (redeclaration)
1) Overloads and scopes
In general, declaring a function locally is an unwise choice. (a function with the same name that is declared in the outer scope is masked instead of overloaded)
In C + +, the name lookup occurs before the type check.
2) function overload determination (overload resolution, which functions match function matching) is the process of associating a function call with a function in a collection of overloaded functions.
3) function overloading determines the procedure:
The first step is to determine the collection of overloaded functions considered by the call. The functions in the collection are called candidate functions (candidate function), which is a function with the same name as the called function, and its declaration is visible at the call point.
In the second step, select the feasible function (viable functions): Select one or more functions from the candidate function, which can be invoked with the arguments specified in the call.
Step three, find the best match
4) argument type conversion
Exact match (exact match)
Matching by type promotion (promotion) implementation
Matching by standard conversion
Matching by class type conversion (Class-type conversion) implementation
5) function overloading can be implemented based on a function reference or pointer parameter that points to a const object or to a non-const object. (You cannot implement overloading of functions based on whether the pointer itself is const)
The parameter is const only if the parameter is a reference or a pointer
18. Pointers to functions
BOOL (*PF) (const string &, const string &);//pf points to Functionbool *pf (const string &, const string &) ; PF is a function that returns a bool*
1) Simplify the definition of function pointers with typedef (see example below)
2) The function pointer can be initialized or assigned using the name of the functor (see example below). (Directly referencing the function name is equivalent to applying the FETCH operator on the function name)
3) A pointer to a function that does not need to use the dereference operator to invoke the function directly through the pointer:
typedef BOOL (*CMPFCN) (const string &, const string &); CMPFCN pf = Lengthcompare; Lengthcompare is the name of a function<pre name= "code" class= "HTML" >lengthcompare ("Hi", "Bye"); Direct call
PF ("Hi", "Bye");
(*PF) ("Hi", "Bye");
4) parameter of function pointer
5) Returns a pointer to a function (the best way to understand it: from the name of the declaration, from the Inside Out)
6) pointer to overloaded function
Ps:4, 5, 6 to be added.
Standard IO Library
The 1.IO type is associated by inheritance, so you can write only one function and apply it to three types of streams: console, disk File, string stream.
2. For some reason, the standard library type does not allow replication and assignment operations (stating the reason for classes and inheritance). There are two layers of meaning:
1) There is no pointer or reference to the stored stream object; (only element types that support branching can be stored in vectors or other container types)
2) parameter and return type cannot be a stream type either. (References and pointers are required when passing and returning IO objects)
C + + Primer 4th reading notes (Part I.)