Read again primer on the one hand is to check leaks, on the other hand is more in-depth understanding of the essence of C + + ideas. The details and understanding of each knowledge recorded in this review are recorded so as to facilitate subsequent warming.
First: Quick Start
1. For statement: for (initialize statement; Conditional test statement; conditional modification expression) {statement Body}. Execution order: The initialization statement executes one time at the very beginning, then executes the conditional test statement, executes the statement body if it is set up, then executes the conditional modification expression, executes the conditional test statement, and then exits the for statement.
2. If Else statement indentation:
if(0==i){ cout<<"i==0"<<endl; }else{ cout<<"i!=0"<<end; }
3, read into the unknown purpose input:
intvaluewhilevalue} sum+=value;//将输入的所有值相加(个数未知)。
The While{std::cin >> value} statement std::cin>>value returns the input stream itself, while the state of the stream is tested to determine if the condition is true. If the status is valid, the test succeeds. Input stream when a file terminator or invalid input is encountered (such as not an integer entered here), the state of the stream object is invalid.
4, and file Terminator: Under Windows press Ctrl+z,unix Press CTRL+D.
5. CIN: IStream object for reading from standard input (cin>>value: reads input into scalar value from standard input via IStream object cin)
Cout: Ostream object for writing to standard output (cout>>value: Output variable values through Osteam object out to standard output)
Standard input: The input stream associated with the Program execution window, which is set by the operating system
Standard output: The output stream associated with the Program execution window, which is set by the operating system.
6. Function arguments: The value that is passed to the calling function. Function parameter: the part of the function definition that indicates what parameters are available to invoke the function.
Chapter 2nd: Variables and basic Types
1. The Computer Associates each byte in the memory with an address. You can use an address to represent any number of different-sized bit sets starting at that address, such as a word with an address of 0x .... (4 bytes) or a byte with an address of 0x. To make a byte (8 bit) meaningful, you must know the type of the value stored on that address. (This type is specified by an additional 4 bytes of overhead) to interpret the data based on the type of the address content, which makes the content of the address meaningful (otherwise, a bit string consisting of 0 or 1).
2. The difference between BOOL and bool False/true and false/true:
BOOL is obtained by # define BOOL int, so bool is an integer, and the same false/true is the integer type of # define, its size is related to the specific compilation environment (integer type is generally 4 byte size, depending on the environment). Its value: BOOL is a typedef int BOOL (in windef.h) defined by Microsoft. It is a three-value logic, True/false/error, when the return value is greater than 0 for an integer when True, the return value is 0, FALSE, and the return value is error 1.
The bool is the new data type in C + + (none of the), the size is one byte, the value is true or FALSE, and the size is one byte. BOOL evaluates to FALSE and true, which is the difference between 0 and 1
3, signed integer: In a byte to explain, the value is 8-7: positive, that is, except for the highest bit of the sign bit (0) low three-bit value (0-7), negative (the highest bit is 1), converted to a complement representation (positive number of the original code is the same as the reverse code, negative number of the original code in addition to the highest bit sign of the negation, And the complement is anti-code plus 1), so 1000, that is, 8: (The inverse code is 1111, the complement is 1111+1= sign bit 1, also left 1111, that is 8, so the result is 8); 1001 is -7,1111 to 1.
The complement is calculated: The variable A is stored with n bits (n does not count the sign bit), and the method of calculating its complement when it is negative is a=-(a+2^n);
4. Assignment of integral type: When assigning a variable to a value beyond its range, the compiler must adjust the period to satisfy the requirement--modulo the value of the number of possible values of the unsigned type, and then obtain its value. If you assign 336 to unsigned char (one byte), the result is 336%256=80; assigning a negative value to the unsigned type in C + + is legal and the result is modulo. If 1 is assigned to the 8-bit unsigned Cahr result is: -1%256=255; (the symbol of the modulus is consistent with the divisor, and the result of the remainder is consistent with dividend)
5, take the mold: Any integer A can be expressed as a=k*b+r, induction: When the A and B symbols are consistent, the calculation of the modulus and the remainder of the calculation of the value of C is consistent, so the results are consistent; When the symbols are inconsistent, the results are different. The symbol of the result of the modulo operation is consistent with B, and the sign of the result of the remainder operation is consistent with a. ( -7 mod 4=1,-7%4=-3).
6, in order to be compatible with the C language, all string literals of C + + are automatically added by the compiler to the end of a null character.
7. Variables provide a named store, so you can use the variable name to refer to the value of the corresponding storage space. Variable names can only consist of letters, underscores, numbers, and cannot begin with a number.
Lvalue: Can appear to the left or right of an assignment statement, such as a variable
Right value: can only appear to the right of an assignment statement, such as literal constants: 5, "abc".
8, two types of initialization: Copy initialization (int i=10;), direct initialization (int i (10);). Direct initialization is more efficient (but basically no difference to built-in types).
9. When no initialization value is specified, the system is sometimes initialized automatically.
Built-in type automatic initialization: variables defined in the function body are initialized to 0 (all variables of uninitialized data segments in process space, such as variables with global unspecified values, global and local unspecified worth of static variables, are automatically initialized to 0 or null pointers), variables with no initial values specified in the function body (data in the stack If an automatic variable is not initialized automatically, its value is undefined and may be random: The data value remaining in the memory address is not automatically initialized.
Initialization of variables of class type: for types with default constructors, you can not display initialization, and for types that do not have a default constructor, you must provide the initialization of the display.
10, variable definition: Used to allocate storage space for the variable, you can also specify the initial value. Variables have and have a definition in a program. The definition contains a declaration.
Variable declaration: Used to indicate a variable type and name, not a definition, or allocate space. Use the keyword extern int i, declare i. Note that the declaration that contains the initializer is considered a definition (the variable was not defined before, and cannot be redefined after that) extern int i=10;
11, const: Define non-literal constants: const int bufsize=512; BufSize is still an lvalue variable, but its value can no longer be modified. The definition must be initialized. The const object defaults to a file local variable, that is, a const variable defined in one file is not available in other files unless it is declared as a global variable: (file1.cc) extern const int bufsize =512//defined and declared as a global variable; DECLARE (file2.cc) extern const int bufszie;//in other files.
12. Reference: A reference is an alias that defines another variable. (only aliases can be defined on variables, not literals such as int &val=10;//error int i; int & val=i;//pairs, but a const reference can be: const int &ref=512; pair, because the reference is just an alias of an existing variable, so the reference does not give the reference extra space.
13, const reference: const int val=1024; const int & refval=val; (int & refval2=val;//error) (For const variables, you must bind to a const reference, not to a non-const reference, otherwise the value of the original const variable is allowed to be changed by reference) , which is not legal). A const reference is a reference to a const object. A const reference can be defined on a non-const variable, at which point the value is modified only by the variable name (of course, the value of the const reference is also variable!). ), and cannot be modified by a reference name.
14. TYPEFEF: Defines an existing type of synonym compile-time processing, and does not introduce a new type. Typedef int int; (formerly known in front); #define则是宏定义, in fact, is an alternative to pre-compilation simple substitution, not for correctness check.
#define int_ptr int * (源在后)//相当于int * a, b; 只是简单的宏替换int* int_ptr; //a, b 都为指向int的指针,typedef为int* 引入了一个 新的助记符
15. Enumeration type (integer constant set) Enum:enum point{A, B, c}; (a default assignment is 0, followed by 1)//defines a new type point; Point p1=a;//defines a variable of point type (note that an enumeration type variable can only be assigned by an enumeration member of its type, or with an enumeration variable of the same type, but not in any other way), (an enumeration member A B c is itself an integer constant that can be used anywhere that a constant expression is required. Arrays-Defined dimensions: int array[c];//defines an array of 2 elements, and a const-defined shape can be used as an array length.
16. Class: The class defines a data member when it cannot be initialized directly, and the data member needs to be initialized with a constructor function. Private data members are accessible only through their member functions, and data members of public can be accessed through object names.
17, CALSS and struct differ only in the default access level.
18. Header files are used for declarations, not definitions: Because header files are contained in multiple source files, header files should not contain definitions of variables or functions (Exceptions: Header files can define class const objects and inline functions, Because the compiler needs their definition to produce the code) (note that for the const variable to have all files globally available, the definition is required to add the extern keyword)
19. Avoid multiple inclusions in header files: #ifnfef AAA #define AAA #endif
3rd chapter: standard Library Types
Standard library String Type:
1, read sting from the standard input, read and ignore the beginning of all white space characters (space wrap tab); Read character instruction this encounters a whitespace character, reading terminates. cin>>str; input: "Hello world! ", then STR is actually" Hello ", the opening whitespace is ignored, and the trailing whitespace is terminated.
2. String io operation: getline (IStream cin,string str); The function reads a line from the input stream and saves it to sting, stopping and returning whenever a newline character is encountered (if the first is a newline, the String object is empty, Note the difference when reading a string with CIN), the return value is a stream object such as CIN, when while (Getline (CIN,STR)); As a conditional statement, the test returns the state of the stream object as in the previous cin>>str. (Ctrl + Z end input)
3. When assigning a string literal constant to a string object, does not contain empty characters that are automatically added at the end of the string, such as String str= "abc", and Str contains only ABC three characters.
4. Do not use int instead of the Strng::size_type type (Strng::size_type is defined as unsigned integer, so its length is twice times of int, if the value of Size_type is accepted with int, it can cause overflow: int i=str.size ( )///The Size_type value that may be returned is greater than the maximum value of int (correct: size_type size_t=str.size ();).
5. Assignment of String object: String str1,str2= "AAA"; str1=str2;//(assign value to STR1: First release the memory of STR1, and then give str1 enough space to hold the str2 copy, and then copy str2 characters to str1 space), so this assignment is inefficient.
6. Connection of string and sub-par strings: string str; Str= "AA" + "BB";//error: At least one of the left and right operands of the connection + number must be of type string.
7. A single character handler in string: header file < Cctype > contains a number of functions that handle a single character: for example ToUpper (str[2]);//convert character st[2] to uppercase and return capital letters; ISPUNCT (STR[2) );//test whether the character is punctuation. Wait a minute!
Standard library vector:
1, subscript operator [], only the existing elements can be manipulated. The operator returns a reference to the corresponding element, so the vector Vec (10,2); vec[2]=100;//makes the third element of VEC 100. As for Sting.
2. All standard library containers define the appropriate iterators, and only a few define subscript operators.
3, pay attention to the iterator failure problem. Any operation that alters the length of the vector, such as push_back, will invalidate the original iterator.
4, Const_iterator iterator: Vector::const_iterator const_iter;//cannot modify the value of its specified element through the iterator. (but can change the element it points to)
5, two of the same type of iterator to get its difference (type is difference_type, the vector is defined as signed alias, similar to Size_type to unsigned). However, two iterators cannot be added, (two pointers are added, not defined).
Standard library Bitset types
Fourth chapter: Arrays and Pointers
Array:
1. The array dimension must be a constant expression (literal constant, enumeration constant, const constant, const + literal constant, or constant) with a large equal to 1.
2. When initializing a character array with a literal string, you cannot forget to reserve space at the end of the string.
3, not allowed to copy and assign the array directly: int a[]={1,2,3}; int b[3]=a; Error (Reason: array name is not modifiable Lvalue: constant pointer)
4, take the address operator can only be used for the left value
5. C + + usedeclares a representation as a pointer. Style: intA with intA; Yes, but you should use the latter, such as: intA, b;//actually only a is a pointer and b is an int. (a B is misunderstood as a pointer), and an int *a,*b;//defines two pointers.
6, the pointer value is 0, indicating that the pointer does not point to any object, avoid the use of uninitialized pointers. If you cannot specify the object when you define the pointer, you should initialize the pointer to 0. (only the literal value of 0 is given to the pointer, but not the integer variable with the values of 0) (preprocessing variable null is 0)
7. The void* pointer can receive the address of any non-const type object, but does not provide the type information of the object on the indicated address, and therefore cannot directly manipulate the object referred to by the Void pointer, such as dereference. Can do comparisons, function parameters, etc.
8. The arithmetic operation of the pointer: when the pointer points to an element in the array, the pointer is added minus N, and a new pointer is given, which points to the nth element before or after the original element. (Note: Adding and minus N does not make the new pointer out of bounds.) Allows you to point to the next position of the last element of the array, that is, the super-tail, but not to dereference the tail, but only as a sentinel, acting like the end () iterator of the vector.
9. Subtract two pointers to the elements in the same array (including the super-tail pointer): Gets the spacing between the two pointers, the type is ptrdiff_t (signed). Two pointers added, is meaningless!!
10, subscript and pointers: using subscript to access the array is essentially a new pointer to the position of the new element by the subscript + original pointer. such as: int a[10]={}; A[5] That is, the first pointer a plus 5 gets a new pointer to the 6th element, while int* p=& (A[5]); p[-2];//because p initially points to the 6th element and then back 12, so p[-2] and is a[3];
11, the array name points to the first element of the constant pointer: can not be ++,– and other operations to change its point to other elements up.
12. The pointer to the next unit at the end of the array is an extra-tailed tail: A sentinel function for comparison to prevent cross-border. But you cannot dereference it. It is not possible to calculate the previous address of the tail and the first address.
13, (pointer constant) pointer to the Const object: const int *p; (can not be initialized) is interpreted as pointing to a constant. That is, the value of your object cannot be changed, but you can change the pointer to another object. You can assign a pointer constant to the address of a non-const object (you cannot change its value by this pointer constant at this point, because it always assumes that the object it points to is a const object).
14, (constant pointer) cosnt pointer: int *const p=&a;//must be initialized. The pointer itself is a constant and cannot be changed to point to other objects. But whether the value of the object is changed depends on whether the object itself is a const object.
15. Const pointer to const object: const int *const p=&a;//must be initialized. The value of the object and the object you are referring to cannot be changed.
16. The identifier of the const modifier immediately thereafter.
17. The type of string literal is the const char array. Always note the null at the end
18. The Standard function library (c + + version of String.h) that handles C-style strings is CString.
19. Initialize the new dynamically allocated array: If the element type is a class type, the default constructor is initialized. If it is a built-in type, there is no initialization value.
string *str=new string [10 ]; //10 elements are initialized to null Int *p=new int [10 ]; //10 elements are not initialized Int *p1=new int [10 ](); //followed by parentheses, requiring the compiler to initialize its elements to 0.
20, string and C-style strings mixed:
(1), string can be initialized and assigned with a C-style string (ignoring the end of null).
(2), the reverse is not true: the C-style string can not be initialized or assigned directly to the value. You can use the member function of string c_str to convert a string to a C-style string. Note: the C_STR () function returns a pointer constant that points to string strings (null at the end).
Example: String str ("AAA"); const char *C=STR.C_STR ();//At this point the C pointer points to "AAA" (with NULL at the end) and then modifies the str:str= "BBB"; The value of C is also changed to the end of "BBB" plus null.
21. Multidimensional array: An array that understands arrays.
(1), int *p[4];//defines the array of pointers: P is an array containing 4 pointers.
(2), int (*p) [4];//p is a pointer to an array that has 4 elements.
The Fifth chapter: Expression
1,% to find the surplus or to take the mold. Its operands can only be of integer type. Divides two integers, the result is an integer, and the decimal is truncated.
2, two expressions are evaluated or computed only if the first expression cannot determine whether the entire result is false or true, the value of the second expression needs to be evaluated, or the second value is not evaluated.
3. Note that string also has iterators: String::iterator it=s.end ();
4. Should not be threaded using relational operators: Relational operators (< <= > >=) with left associativity: if (i
void func(int &a[10]);//元素为引用的数组void func(int (&a)[10]);//这才是数组的引用,括号不可少int *a[10];//表示10个指针的数组Int (*a)[10];//表示数组的指针;括号不可少
Can be understood as:* and & forward combination.
3, multidimensional array is an array of arrays: multi-dimensional array parameters in addition to the length of the first bit is not specified (as one-dimensional, the compiler automatically ignores), other dimension length must be explicitly specified. A pointer to an array when actually passed in.
4, return reference, return a constant reference. You must not return a reference or pointer to a local object.
5, Function declaration: return type, function name, parameter list, these three elements are called function prototypes, describe the function interface.
6. Function default argument: When declaring or defining, if one of the arguments specifies a default argument, then all arguments thereafter specify the default argument, and conversely, if a parameter is passed to one of the arguments at the time of invocation, then all the arguments before that parameter should show the incoming argument, and the default argument value fills the last vacant parameter. A function default argument can be specified at the time of function declaration as well as in a function definition, but different at the same time. Typically specified in a declaration.
7. Inline functions: Avoid the overhead of function calls, but this is only a recommendation to the compiler. Inline functions must be defined in the header file.
8. member functions of a class: The function body can be defined either in the class or outside the class. The compiler implicitly considers member functions defined inside the class as inline functions.
9. Each member function implies an additional parameter: the this pointer, which is a pointer to the object that called the function. For example, the use of other member variables of its object in the function is called through the implied argument.
10, the constant member function: that is, the function of the declaration of the formal parameter list after the keyword const. This makes the object calling the member function a const object, which is a pointer constant, pointing to a const object, so that the member of the object cannot be changed in that member function. Note: The declaration must be consistent with the definition, and when the declaration is const, it must also be defined.
11. Note: A const object, a pointer to a const object, or a reference, can only be used to call a const member function and is an error if you attempt to invoke a non-const member function. (The object may be modified if a non-const member function is called, because they indicate that no member of the object is modified)
12. This pointer: Contains the this pointer parameter that cannot be displayed in the formal parameter list of a member function, and any member that uses its object without a prefix in the function body is assumed to be called through the this pointer. (a member that can be displayed in the function body using the this pointer to invoke its own object, is a legitimate:this->member;)
13, constructor: The constructor is placed in the public section, there is no return value, you can take the initialization list (the argument list and the function body's curly braces, beginning with:)
(1), default constructor: Indicates what to do if the provided initialization is not displayed, without providing any initial value. (if no constructors are defined for the class display, the compiler automatically generates a default constructor that typically applies only to classes that contain only class type members, classes that contain built-in type members, and should define default constructors themselves)
(2), initialization list of constructors: Specifies the initial value for one or more data members of a class. such as Class A: constructor: A (): Intmemb (0), Doubmemb (0.0) {};//does not have a data member given an initial value, invokes its own default constructor for initialization.
14. Function overloading: Multiple functions in the same scope, with the same function name, and the formal parameter list are overloaded (the main function cannot be overloaded) (note that the name of the inner scope overrides the function or variable of the outer scope)
15. The function cannot be overloaded only based on the difference of the return type (if the parameter list of two functions is the same, but the return type is different, the second function declaration is wrong)
16. Choose the three steps to determine the overloaded function: Look for a set of candidate functions, select all the feasible function (including exact matching, type conversion matching), and find the best match. (If one of the best matches is not identified, the call is ambiguous, and an error occurs) (type promotion is better than standard conversion
17. If the formal parameter is const only if the parameter is a reference or pointer, it can only be overloaded by Const. (such as arguments: references and common references can be used to overload; non-references and const non-references are not possible, because both are copies of the arguments, and the arguments are either const or non-const) to the pointer in the same vein: (F (const int) and f (int) is overloaded;; F (int *) and F (int *const); not overloads, both accept constant or non-const pointers, both are copies)
18. Function pointers: Like other pointers, a function pointer is a specific type, and the function type is determined by its return type and argument list, regardless of the function name.
19. Returns a pointer to a function: Int (func (int)) (int, int);
Inner to outer comprehension: Inside: func (int): Func is a function with an int parameter. The return value (outer) of the function is: Int () (int, int); Such a function pointer.
The typedef can be used to make it easy to understand:
Typedef Int (PF) (int, int);//defines a function to point to with two parameters (an integral type refers to the
Needle, an integer) and a function pointer that returns a type of int.
PF ff (int),//FF is a parameter of int and returns a function of the type PF.
eighth: Standard IO stream (standard input output stream file stream string stream)
1, IO Standard object cannot be copied or assigned: The IO reference or pointer must be passed when the Io object needs to be passed. Because read and write to an IO stream object alters its state, a const reference cannot be passed.
2, Output buffer management: A few things will cause the output buffer to be flushed, that is, to write to the true output device or file:
(1) The program ends normally: main returns to the part of the work, and all buffers are emptied.
(2) at some indeterminate time, the buffer is full
(3) shows the operator that called the flush buffer: ENL flush ends, etc.
3. Note: When a program crashes, the buffer does not flush, so when you debug a program based on output, you need to ensure that each output is successfully flushed out to the device. Therefore, use Endl to flush the output each time it is output.
4, when an input is associated with an output stream, any attempt to read the input stream will first flush the output buffer. The standard library associates the CIN cout. cin>>ival; causes the cout associated buffer to be refreshed. The function tie can be used to associate an output stream input stream.
5. Use of a file stream object: (You need to define two file input and output stream objects yourself) header text
#include <fstream> Ifstream ifile; //file input stream object (not associated to file) //output stream, initialize association to the given path file (C-style) ofstream ofile ( "c:desktop\\ Test (2). txt "); Ifile.open ( "C:desktop\\test (2). txt" ); //Association ofile<< "where is you?" <<endl; //writes data to the file string str ; Ifile>>str ; //read data from a file: As with CIN, you encounter a blank getline (ifile,str ); Span class= "Hljs-comment" >//the file that is associated with the file input stream is read into a line to str cout<<str ; //output to standard output device
Note: After opening the file, remember to check whether the open is successful
if (!ifle)//If unsuccessful then prompt. In addition, once the fstream is open, it remains associated with the specified file, to associate the file stream object to another file, you must close the close current file, then open the other file, and you need to call the clear function to clear the stream state identity before opening again.
6, open the file when opening the attention to set the open mode. If you want to keep existing content when you open a file with Ofstream, you must display the file set as app open mode. Ofile ("filename", Ofstrream::app);
7, FStream stream object, both can read and can write open files.
8. String flow: Bind the Stream object Sstream (need to include the header file Sstream) with the string object to read and write string strings through Sstream
C++primer (Fourth edition) Review notes-First: Basic language