Traditional Culture Encyclopedia - Traditional customs - Advanced C++ grammar

Advanced C++ grammar

C Basic Grammar (1)

0. When compiling C program, the compiler automatically defines a preprocessing name __cplusplus, and when compiling standard C, it automatically defines a name __STDC__. Other useful predefined names are __LINE__ (the current number of compiled lines of the file), __FILE__ (the name of the currently compiled file), __DATE__ (compilation date) and __TIME__ (compilation time).

C name of the header file of 1 C library always starts with the letter c, followed by the suffix c name. H, as in library C, the name is. Two methods of use:

# Contains or

# Including

Use namespace std

2. Two main differences between static and dynamic memory allocation: (1) Static objects are variables with names, which can be operated directly, while dynamic objects are variables without names, which can be operated indirectly through pointers; (2) The allocation and release of static objects are automatically handled by the compiler, while dynamic objects must be explicitly managed by programmers and completed by two expressions: new and delete.

3. The default constructor of the class does not require the user to provide any parameters.

4. There are two traversal methods for standard array vectors (files) in 4.STL: (1) through subscript operators; (2) Use iterators, such as vector.

5. Literal constants are not addressable.

6. Several commonly used escape sequences:

Newline \ n \14

Horizontal tab \t

Vertical tab \v

Backspace (backspace) \b

Enter \r

Formfeed (feed key) \f

Alarm (bell) \a \7

7. Both variables and literal constants have storage areas, the difference is that variables are addressable, and for each variable, there are two values associated with them: the data value, called the right value of the object, is a read value, and both literal constants and variables can be used as right values; The address value, called the left value of the variable, is the position value, and the literal variable does not need to be used as the left value.

8. Each pointer has an associated type. Pointers of different data types differ in the type of object the pointer points to. If all we need is to save the address value, C provides a special pointer type: null * pointer, which can be assigned by the address value of any data pointer type except function pointer. You can't manipulate the object pointed by the null pointer, you can only pass the address value or compare it with other address values.

9.c-style algorithm cycle:

while(*p ){…}

10. Define the reference correctly, as follows:

const int ival = 1024;

Const int * & amppi_ref = & ampival///error, pi _ ref is a reference to a pointer to an int object defined as const. The reference does not point to a constant, but to a non-constant pointer.

Constant int * constant & amppi _ ref = & ampival///Okay.

1 1. There are two main differences between pointers and references. A reference must always point to a variable; If one reference assigns a value to another reference, it is the referenced object that changes, not the reference itself.

12. Although an object of Boolean type is also regarded as an object of integer type, it cannot be declared as signed, unsigned, short or long.

13. An array cannot be initialized or assigned to another array, and C is not allowed to declare a reference array.

14. The array identifier indicates the address of the first element in the array. Its type is a pointer to the type of an array element.

int ia[ 10];

The address of the first element: ia or&; ia[0]

Address of the second element: ia 1 or&; ia[ 1]

There are two different ways to use vector in 15.STL: array habit, that is, using subscript operator, paying attention to only operating existing members; STL is used to operating with iterators. You can access the actual object by dereferencing, or you can move the position by adding and subtracting. Similarity and 5.

Typedef is used to introduce mnemonics for built-in or user-defined data types.

typedef char * cstring

External constant cstring cstr

The type of cstr is char * const cstr.

17. When the value of an object may be changed outside the control or supervision of the compiler, then the variable should be declared as volatile, and some routine optimizations performed by the compiler cannot be applied to objects that have been designated as volatile.

18.pair class can associate two values of the same type or different types in a single object. We can use member access symbols to access individual elements in a pair. Their names are number one and number two.

19. Inline member functions defined outside the class should be contained in the header file containing the class definition.

20.setw () is a predefined iostream operator, and the maximum number of characters it reads is the parameter passed to it minus one. Such as setw( 1024), the maximum number of characters is 1023.

The 2 1. standard C header file provides information about the built-in type representation. In addition, there are standard C header files and.

22. For binary operators, the calculation order of left and right operands is not defined in standards C and C, so the calculation process must be independent of the order. For example, ia[index] is undefined.

23. The initialization process provides the initial value for the object, while the assignment is to overwrite the current value of the object with the new value. An object can only be initialized once, that is, when it is defined, the assignment can be repeated. Such as initializing intival =1024; Assignment ival =1025; The left operand of an assignment operator must be a left value.

24. the function of sizeof operator is to return the byte length of an object or type name, and the return value type is size_t, which is a machine-related typedef definition, and its definition can be found in the file.

25. Flip each bit of the operand by the bitwise NOT operator (~). The shift operator (>) shifts the bits of its left operand to the left or right by some bits, and the bits moved to the outside are discarded. The left shift operator fills the space with zeros from the right. The right shift operator, if it is an unsigned number, inserts 0 from the left, otherwise it either inserts a copy of the sign bit or inserts 0, which is defined by the specific implementation. Bitwise and (&; ) and each bit of the two operands (the value is 1 only if both bits are 1). The bitwise XOR () operator XOR each bit of two operands (only two operands with a value of 1 are 1, that is, two different values are 1). The bitwise OR (|) operator performs an OR operation on each of the two operands (only if both bits are zero at the same time). If the 27th bit of the integer A is set to 1: A | = 1

26.bitset class, with header file as, supports three construction methods. The first is to specify the vector length directly, such as Bitset.

27. Operator Priority Table

28. Implicit conversion occurs in the following situations: 1. Mixed arithmetic expression, namely arithmetic conversion; 2. Use one type of expression to assign a value to another type of object; 3. Pass the expression to the function call, the type of the expression is different from the type of the formal parameter; 4. Return an expression from the function.

29. Two principles of arithmetic conversion: 1. If necessary, the type is always promoted to a wider type; 2. Before calculation, all arithmetic expressions with integer values less than integer values will be converted into integer values.

30.const_cast transforms the constancy of expressions and the variability of changeable objects; Such as const _ cast

3 1.typename is a new keyword introduced in standard C and used in template.

32. The two main sequential containers are list and vector, and the other sequential container is deque;; The two main association containers are map and set.

33. Some criteria for selecting sequential container types: (1) Random access, vector is much better than list; (2) If the number of elements is known, the vector is stronger than the list; (3) If you don't just insert and delete elements at both ends of the container, list is much better than vector; (4) vector is better than deque, unless you need to insert and delete elements in the container header. For small data types, the performance of vector inserting a large amount of data is much better than that of list, while for large data, the opposite is true. The solution is to keep only pointers to big data. The Reserve function allows the capacity of the container to be set to a clearly specified value, and the resize function resets the length of the container; Each container supports a set of relational operators; User-defined class types must support equal operator and less operator, and element types must support default values (default constructors for class types).

34. In addition to the iterator type, each container also defines a const_iterator type, which is necessary to traverse the const container. Const_iterator allows read-only access to the underlying elements of the container. Iterator arithmetic operations (arithmetic operations such as addition or subtraction, not overloaded operators) only apply to vector or deque, but not to list, because list is not stored in memory continuously.

35. The find function of String class returns the index type of string::size_type or string::npos; ; Find_first_of provides the first occurrence of any character in the search string and returns its index position. The substr function generates a copy of the substring of an existing string object, with the first parameter indicating the starting position and the second optional parameter indicating the length of the substring. Rfind, to find the match of the last specified substring; Find_first_not_of finds the first character that does not match any character in the string to be searched; Find_last_of finds the last character that matches any element in the search string; Find_last_not_of finds the last character in the string that does not match any character in the search string.

36. The 36.tolower function accepts uppercase characters and returns their lowercase equivalent. It must include the header file and some other functions in the file, such as isalpha, isdigit, ispunct, isspace, toupper, etc.

37. Assign a value to the string; Append is similar to the = operator; Swap exchanges the values of two strings; The at that performs the out-of-bounds check is similar to the [] operator; Compare function provides dictionary order comparison of two strings; The replace function provides ten ways to replace one or more existing characters in a string with one or more characters.

38.map defines a type value_type, which represents related key-value pairs and is used for the insert function.

39. The association container supports the following two functions: find to find the specified key, and return end () if it does not exist; Count returns the number of occurrences of the specified key value.

40.set defines a type difference_type, which is the result type of subtraction between two iterators; The inserter class is used to perform an insert operation. Such as: copy (in, EOS, inserter (set 1, set 1. begin()); Because the copy performs the assignment operation, the inserter is used instead of the assignment operation.

4 1 special operation equal_range. Multiset and multimap return iterator pair values, such as: pairpospos = mp.equal _ range (tst);

42. The stack class, header file, function top and pop access and delete the top element of the stack respectively. The stack type is a container adapter because it applies stack abstraction to the underlying container. By default, the stack is implemented by deque, and the default underlying container can be customized, such as using list to build stack: stack.

43. In C, the array is never passed by value, it always passes the pointer of the first element (to be precise, it is zero). A multidimensional array is passed as a pointer to the 0th element. For example, matrix[][ 10] is equivalent to int (*matrix)[ 10], which means that matrix is a two-dimensional array with 10 columns in each row. And int *matrix[ 10] represents an array containing 10 pointers to int.

44. The 44.UNIX system function chmod changes the protection level of files, and its function is declared in the system header file.

45. The first form of link indicator consists of the keyword extern followed by a string constant and an ordinary function declaration, such as extern "c" void exit (); The second form is to include multiple function declarations in a compound statement with braces for the relink indicator. Link indicators cannot appear in functions, they are more suitable in header files.

46. Main function supporting command line format: int main(int argc, char * argv []);

47. Pointers to functions, such as int (* pfunc) (int, int); Pointers to this type can also be generated by applying an address reader to the function name. If the function definition int f 1(int) already exists; int(* pf 1)(int)= f 1; int(* pf2)(int)= & amp; f 1; The function call can be in the format of pf 1( 1) or (*pf 1)( 1). When a function name is not decorated by the calling operator, it will be interpreted as a pointer to this kind of function, such as the function definition int f (int); The expression f is interpreted as int (*)(int).

48. Definition of function pointer array: int (* testcases [10]) (); Using typedef can make the declaration more readable. Such as typedef int(* PFV)(); (); PFV test case [10]; Declare a "pointer to function pointer array", such as PFV (* parlay) [10]; Call function (* parlay)[2](); [2] ();

49. The type of function parameter can't be a function type, and the function type will be automatically converted into a pointer to the function type. If there is a function type typedef int funtype (int); void sort(int,funtype); And function definition sort(int, int (*) (int)); The equivalent function pointer can also be used as the type of function return value, such as int (*ff(int))(int *, int); This declaration declares ff as a function, which has an int parameter, and the return value is a pointer to the function, of type int (*) (int *, int);

50. The pointer to the c function is different from the function pointer to c, that is, the types of int (*fcpp)(int) and extern "c" int (* FPC) (int) are different. And when the link indicator acts on a declaration, all the functions it declares will be affected, such as extern "c" void f1(void (* pfparm) (int)); Where pfParm is also a c function pointer. Therefore, to realize a C function, you can use typedef, such as Extern "c" TypeDef VoidFC (int), with a C function pointer as a parameter. C function void F2 (fc * pf param);

The 5 1. keyword extern provides a method of declaration rather than definition. Extern declarations do not result in memory allocation.

52. Header files should not contain definitions of non-inline functions and objects. The definitions of symbolic constants and inline functions can be repeated many times. At compile time, the values of symbolic constants will replace the appearance of names when possible, and this process is constant folding. A symbolic constant is any object of type const. But the following definition does not conform to char * constbuf = newchar [10]; Because its value cannot be determined at compile time or defined in the header file; Const char * msg = "Error Because msg is not a constant, it is a non-const pointer constant value and must be modified to const char * const msg =.

53. There are three kinds of local objects: automatic objects, registered objects and local static objects. Variables frequently used in functions can be declared as register objects using the keyword register.

54. The delete expression can only act on the pointer allocated from the free storage area by the new expression. It may cause problems if it acts on other memory pointers, but when it acts on a pointer with a value of 0, delete will not point to any operation.

55.auto_ptr is a class template provided by STL, which can help programmers to automatically manage a single object dynamically allocated with new expressions. The header file is that only the object with the ownership of the underlying object is responsible for releasing the memory, but when using the copy constructor and assignment, the object on the left obtains the ownership, while the object on the right is revoked. Use get to test whether it points to the underlying object, use reset to reset the underlying object, and the assignment operator does not support memory pointers.

56. You can create dynamic const objects, such as Consint * PCI = New Consint (1024); Cannot create an array of constant objects. The created constant objects must be initialized.

57. Positioning new expressions allows programmers to request the creation of objects in allocated memory. Such as: char * buf = newchar [1024]; Foo * Pb = new(buf)Foo;

58. You can use an unnamed namespace to declare the local entity of a file, that is, the function is only visible in the current file. Usually used in implementation files, this method is used to replace static function declarations in C language.

59. Overloaded function, two functions have the same function name, but the function parameter table must be different, and the number or type of parameters are different; The identification function declaration does not consider whether the type of the passed parameter is const or volatile, that is, void f(int) and function void f(const int) are the same function. However, these two modifiers need to be considered when passing addresses or references. Void f(int *) and function void f(const int *) are different functions.

60. All functions in the overloaded function set should be declared in the same domain. Using declarations and indicators can make members of one namespace visible in another namespace, which will affect the overloaded function set. The using declaration always declares aliases for all functions that overload functions. If the imported function already exists in the domain and the parameter table is the same, an error will occur. The external "c" link indicator can only specify one function in the overloaded function set.

6 1. Three Steps of Function Overload Analysis (1) Determine the set of overloaded functions considered in the function call and determine the attributes of the independent variable table in the function call; (2) Select a function from the overloaded function set, which can be called with parameters under given conditions; (3) Select the function that best matches the call. The second step, the compiler determines the required parameter conversion and classifies it, which is usually divided into exact matching; Matching type conversion; Do not match. Among them, type conversion is usually divided into three groups: promotion, standard conversion and custom conversion.

62. Exact matching details: Even an argument must be converted into the type of the corresponding function parameter by applying some minimal type conversion; These minimum types of conversions include: conversion from left value to right value; From array to pointer; The exact match between conversion from function to pointer and qualified type conversion (usually const and volatile type conversion) can be achieved by explicit coercion, in which case, the parameter type is the converted type.

Basic Grammar (Part II)

0. The prompt in type conversion is actually the promotion of built-in data types, such as char to int, bool to int, float to double.

There are five standard conversions in 1. type conversion: (1) integer value type conversion (excluding promotion); (2) floating-point conversion; (3) conversion from floating point to integer; (4) pointer conversion and (5) Boolean conversion. The first three conversions are potentially dangerous. All standard transformations are equivalent. Some notes: 0 can be converted to any pointer type, so the created pointer is called null pointer value, and 0 can also be any integer constant expression. Constant expressions 0L and 0x00 belong to integer value types, so they can be converted into null pointer values of int *. Pointer conversion allows parameters of any pointer type to be converted to void *, but function pointers cannot be converted to void * according to the standard.

2. For the reference parameter, if the argument is a valid initial value of the reference, it is an exact match, otherwise it is a mismatch.

3. The template non-type parameter represents a constant expression, which consists of a public parameter declaration, indicating that the parameter name represents a constant of the template definition type. When instantiated, the constant is replaced by a constant value known at compile time.

4. In the template, in order to support type expressions, typename must be used; Such as typenameparam:: name * p; Define a pointer p; If typename is not used, the expression is a multiplication. In addition, the template function can also be declared as inline or extern, and the indicator must be placed after the parameter template. Such as template

5. Three types of transformations are allowed in the derivation of function parameters: (1) left value transformation; (2) Qualified transformation (constant and variable index); (3) Convert to base class: If the argument is a class, it has a base class instantiated from the class template designated as a function parameter; Such as the following code: template

6. You can explicitly specify template parameters, which are explicitly specified in a comma-separated list, followed by the name of the function template instance; Like min

7.c supports two template compilation modes: inclusion mode and separation mode. In the inclusion mode, the definition of function template is included in the file where each template is instantiated, and the definition is often placed in the header file; In separation mode, the declaration of the function template is placed in the header file, and its definition is placed in another implementation file. The definition of the function template in the implementation file must use the keyword export.

8.c supports explicit instantiation of templates, and the definition of function templates must be given in the file where the explicit instantiation declaration is located. Such as template

9.c supports explicit and special definitions of templates, such as template.

10. Throwing an exception can be achieved by throwing an expression. If you throw a popOnEmpty (class object) exception, the expression is throw poponempty (); At the same time, in the catch clause, in order to prevent the copying of large class objects, the exception declaration of the catch clause can be changed to reference.

1 1. When looking for a catch clause to handle the thrown exception, compound statements and function definitions will exit because of the exception. This process is called stack extension. C guarantees that with the development of the stack, all destructors will be called, although the life cycle of local class objects ends because of throwing exceptions. To re-throw an accepted exception, use the throw statement; If you want to modify the received exception object during re-throwing, you must change the exception declaration of the catch clause to a reference.

12. The exception specification follows the function parameter table, which is specified by throw, followed by the exception type table. Such as void pop(int & amp; value)throw(popOnEmpty); The exception specification guarantees that no exception that does not appear in the exception type table will be thrown. If the runtime throws an exception that does not appear in the exception type table, the system calls the unexpectedly defined function in the C standard library and directly calls the terminate function to end the program. An empty exception specification does not throw any exceptions.

13. The exception description can be pointed out in the function declaration. When initializing a pointer with an exception specification, the exception specification of a pointer used as a right value must be the same as or stricter than that of a pointer used as a left value. Of course, the parameter type tables must be the same.

14. Use function pointers to adapt the template to more situations. The template of the built-in function pointer declaration is defined as follows: template