The notes are messy and you have to look up from the bottom.
Open an output file: ofstream OUTFILE ("Copy. Out", ios_base: Out); // file name, open mode
Ios_base: Out output mode ios_base: append mode. If the output mode opens an existing file, the number
Data will be discarded. If the append mode is enabled, new data will be added to the end of the file. In both modes, if the file does not exist, the program will create
A new file.
Open an input file: ifstream infile ("FILENAME ")
OUTFILE. PUC (CH); infile. Get (CH)
We can either read a string in the form of a C-style character array or a string type.
The advantage is that memory related to strings can be automatically managed.
While (CIN> ival) reads a sequence from the standard input, knowing that CIN is false, there are two conditions that will make an istream
The object is calculated as false: Read the end of the file (in this case, we have read all the values in the file correctly) or encounter
Invalid value, such as 3.1515926
By default, all blank spaces are lost. If you want to read blank spaces, you may want to retain the original input format or
Handle blank spaces. One way is to use istream's get () (ostream corresponds to put );
By default, the false text value is input as 0, and the true text value is output as 1.
Max (INT val1, int val2) {cout <(val1> val2 )? Val1: val2 ;}
Max (10, 20) outputs 0 because the priority of <is higher? Limited level
The correct result should be: {cout <(val1> val2 )? Val1: val2 );}
When you use the iostream library in a program, you must include the relevant header files, such as # include <iostream>
Input and Output operations are provided by the istream (input stream) and ostream (output stream) classes.
Ostream is derived and allows two-way input/output. For convenience, this library defines three standard stream objects:
(User terminal read/write operations)
Cin: indicates the standard input istrem object, which enables us to read data from the user terminal.
Cout: ostream object that represents the standard output. cout enables us to write data to the user terminal.
Cerr.
Read/write operations on files: Include <fstream>
Ifstream: Derived from istream, binds a file to a program for input.
Ofstream: Derived from ostream, binds a file to a program for output.
Fstream: Derived from iostream, binds a file to a program for input and output.
Because the fstream header file also contains the iostream header file, we do not need to include both files.
/* File * FP, * outf;
Int ch;
While (CH = fgetc (FP ))! = EOF)
{
Cal [CH] ++;
In_num ++;
}
Fclose (FP );*/
========================================================== ========================================================== =====
The overloaded operator is declared in the class body in the same way as a common function, except that its name contains the keyword operator,
And a predefined operator that follows.
Class initialization can be replaced by the following method: A member initialization table is a list of member names separated by commas (,) with their initial values. Member Initialization
The table can only be defined in the constructor definition, rather than in its Declaration. The initialization table is placed between the parameter table and the constructor body
Start with colon.
If a class declares a constructor that contains multiple parameters but does not declare the default constructor, the definition of each class object is
Required parameters must be provided. In practice, if other constructors are defined, it is also necessary to provide a default constructor.
Nested class: unless the peripheral class is declared as a friend of the nested class, it does not have the right to access the private member of the nested class.
If you want to authorize a private member of the peripheral class, you must declare it as a friend of the nested class.
Bit-field: It can be declared to store a specific number of BITs. The bit field must be of an ordered data type, located behind the identifier
Colons, and then a clear expression to specify the number of digits. For example:
Typedef unsigned int bit;
Class File
{
Public:
Bit A: 7;
Bit B: 8;
Bit C: 6;
}
Union is a special class. Data members in a union are stored in the same memory, and each data member is in the same
Memory address. The number of buckets allocated to the Union is the amount of memory required to "include its largest data member.
Static member functions access static data members
S2 is a pointer expression for a certain type of objects. S2-> height () can be written as (* S2). Height () and the results are identical.
A friend may be a namespace function, and a member function of another class defined earlier may also be a complete
Class. When a class becomes a Member, all member functions of the member class are granted the right to access "non-public members authorized to the Friendship class.
Information Hiding:
Public members: can be accessed anywhere in the program.
PRIVATE: It can only be accessed by [friends] of member functions and classes.
Protection member (protected): For a derived class, like public, for other programs, like private.
The default value is private.
Except for static data members, data members cannot be explicitly initialized in the class body, for example, class firts {int meni = 0 ;}
++ ++ ++
++ ++ ++
The C ++ language requires that the iterator bound to the const vector must also be a const iterator.
Const vector <int> VEC; vector <type>: const_iterator iter = Vec. Begin ();
Throw an exception: In C ++, exceptions are often implemented using class classes. For example, class poponempty ();
Throw poponempty (); // throw an exception. It is a constructor expression.
The try block must enclose the statements that can throw exceptions. The try block starts with the keyword try, followed by a sequence of statements enclosed in curly brackets.
A try block is followed by a group of processing code called catch statements.
Try {...} catch (pushonfull ){...}
Catch (poponempty ){...}
If a catch clause does not contain a return statement, after the catch clause completes its work, the program will be executed at the end of the catch clause list.
The exception handling mechanism of. c ++ cannot be recovered. Once an exception is handled, the execution of the program cannot be
Throw to continue.
-------------------------------------------------------------------------
422 int min (INT (& r_array) [size]) {...}
300
In C ++, an array is never passed by value. It is a pointer to the first element. The length of the array is not part of the parameter type.
The number does not know the actual length of the array passed to it. A common mechanism is to provide an additional parameter containing the array length.
Another mechanism is to declare the parameter as [array reference]. When the parameter is an array type reference, the array length becomes the parameter and
As part of the real parameter type, the compiler checks whether the length of the array real parameter matches the length specified in the function parameter type.
Example: void putvalue (INT (& ARR) [10])
A parameter can be a multidimensional array. Such a parameter must specify the length of all dimensions other than the first dimension.
Example: void putvalue (INT matrix [] [10], int rowsize)
INT (* matrix) [10]; // a two-dimensional array. Each row consists of 10 column elements.
Int * matrix [10] // an array containing 10 pointers to the int
[] Has a higher priority *
-------------------------------------------------------------------------
If the return type of the two functions exactly matches the parameter table, the Second Life is the first repeated declaration.
The return type of the function is insufficient to distinguish two overloaded functions.
The empty class size is 1;
All components in the Standard C ++ library are declared and defined in a namespace called STD.
The functions, objects, and class templates declared in <vector> or <iostream>) are declared in the namespace STD.
The simplest solution is to add the using indicator after the # include indicator as follows:
Using namespace STD;
Dynamic Allocation of constant objects: const int * PCI = new const int (1024); // must be initialized, and const must exist before and after
The C-style string char * STR = "123456789" has a length of 9 and the actual occupied space is 10, all of which end with an empty character.
Wait for an extra byte space, sizeof = 10; strlen = 9;
Char * str2 = new char [strlen (STR) + 1]; otherwise, a memory error occurs.
Strcpy (str2, STR );
Apply for a dynamic two-dimensional array:
Int ** Pi = new int * [m];
For (INT I = 0; I <m; I ++)
Pi [I] = new int [N];
For (I = 0; I <m; I ++)
Delete [] PI [I];
Delete [] PI;
Three Common pointer errors:
1. failed to apply the delete expression, so that the memory cannot be returned to the idle storage zone, which is called Memory leakage. (Memory Leak)
2. Two Delete expressions are applied to the same memory. Usually, when two pointers direct to the same dynamically allocated object
A pointer releases an object. The memory of this object is returned to the idle storage area and then allocated to another object. Then, it points to the old object.
And the new object disappears.
3. After the delete operation, the pointer is not set to 0;
If (Pi! = 0) delete PI; // unnecessary. If the pointer operand is set to 0, C ++ will ensure that the delete expression will not be called.
Use the delete () operator, so there is no need to test whether it is 0.
Idle pointer is a root cause of program errors and is difficult to detect. A better way is to release the object pointed to by the pointer
The pointer is set to 0, which clearly indicates that the pointer no longer points to any object.
The delete expression can only be applied to the delete table in the directed memory by using the new expression from the [idle storage zone [allocated pointer.
A dashboard application directs to a pointer to memory outside the free storage area, causing undefined behavior during the program running.
For example: int I = 8; int * Pi = & I; Delete PI; // insecure. If the PI points to I, it is a local object and a memory error occurs during running.
Int * Pi2 = new int (9); Delete Pi2; // Security
The dynamically allocated objects are allocated in the [memory pool of the idle storage area] of the program. One feature of the idle storage area is that
Like no name, the new expression does not return the actually allocated object, but returns a pointer to the object, all operations on the object
The second feature is that the allocated memory is not initialized, and the memory in the idle storage area contains random
Bit mode, which is the result of the last use of the memory before the program runs.
Because the free storage area is a limited resource, when we no longer need the allocated memory, we should immediately return it to the idle storage area.
Storage area, which is very important.
The local object is introduced in the variable declaration in the local field. There are three types of local objects: Automatic Object, register pair
Register object)
Automatic Object Storage Allocation occurs when the defined function is called, the storage area allocated to the automatic variable comes from [program operation
Row Stack], which is part of the function activity record. uninitialized automatic objects include a random bit mode, which is the last time the storage area was
When the function ends, its activity records are popped up from the running stack and associated with the automatic object.
Is actually released.
Automatic variables frequently used in functions can be declared using regester. If possible, the compiler will load the object
In the machine register, if not, the object is still in the memory.
For (register int IX = 0; ix <SZ; ++ IX );
Declare a local object as static and keep the local object that exists throughout the program running. When the value of a local variable is
When it must be valid between multiple function calls, we cannot use normal automatic objects. The value of automatic objects is
Discarded. It can be declared as static. The static local variable object is automatically initialized to 0 by the program;
Void FUC () {static int depth ;}
Extern provides a method for declaring but not defining an object, which promises that the object is defined elsewhere: or
Other places of the text file, or in other text files of the program, such as extern int I; the keyword extern can also be in the function
Specified in the number statement.
During name resolution, the domain search order is from the inside out, so the declaration in the peripheral domain is hidden by the declaration of the same name in the nested domain.
The general context used to distinguish the meaning of a name is the scope. c ++ supports three forms of domain: local scope, name
Namespace scope, Class scope ).
Name resolution is the process of associating a name in an expression with a declaration.
Function parameters cannot be of the function type. function parameters are automatically converted to pointers of the function type.
Int sort (string *, string *, INT (*) (const string &, const string &));
Equivalent to typedef int (* pfi2s) (const string &, const string &);
Int sort (string *, string *, pfi2s );
INT (* testcases [10]) (); // function pointer Array
Equivalent to: tepedef int (* PFV )();
PFV testcases [10];
Function pointer initialization and assignment: int lexicocompare (const string & S1, const string & S2 ){...}
The function name lexicocompare is interpreted as a pointer to int (*) (const string &, const string &).
Function names can also generate pointers to the function type. Therefore, the lexicocompare and & lexicocompare types are the same.
, The pointer to the function can be initialized as follows:
INT (* PFI) (const string &, const string &) = lexicocompare;
Or int (* pfi2) (const string &, const string &) = & lexicocompare;
Only when the parameter table and return type of the pointer on the left of the copy operator exactly match the parameter table and return type of the function or pointer on the right,
Initialization and assignment are correct.
When using function pointers, use pf (IA, size) or (* PF) (IA, size) instead of * PF (IA, size );
Function pointer: The function name is not part of its type. The function type is determined only by its return value and parameter table.
Int * PF (const string &, const string &); No
INT (* PF) (const string &, const string &); yes
In fact, the command line option is the main () Real parameter.
Int Mian (INT argc, char * argv []) {...}
Argc: Number of command line options. argv contains argc C-style strings, representing the Command Options separated by spaces. argv [0] is always
The command is set to the currently being called, from Index 1 to argc-1 indicating the actual option passed to the command.
**************************************** *********************************
Calling a function has a serious drawback: calling a function is much slower than directly calculating it. Instead of copying real parameters, you must save the machine's registers,
The program must also switch to a new position. The inline function provides a solution. It will call each of
Point is expanded by "inner". A recursive function cannot be fully expanded at the call point (although the first call is acceptable). A large function also
It is unlikely to expand at the call point. In general, the inline mechanism is used to optimize small functions with only a few rows that are frequently called.
To replace a large parameter table, a programmer can declare a parameter as a class (or struct), array, or a container type.
A number can be used to contain a set of parameter values. In a similar case, a function can return only one value. If the program requires to return multiple values
The programmer can declare some function parameters as references. In this way, the function can directly modify the real parameters, or declare a function.
The return type is a class or a container type that can contain a set of returned values.
Various functions in a program communicate through two mechanisms. One method is to use global objects, and the other is to use function parameters.
Table and return value.
By default, the return value of a function is passed by value. The life cycle of a local object ends with the end of the function. After the function ends
In this case, the return type should be declared as a non-reference type, and then
Copy the local variable before the end of the lifecycle.
The function returns a left value. Any modification to the return value will change the actual object to be returned.
Ellipsis parameter: When we cannot list the types and numbers of all real parameters passed to the function, we can use the ellipsis (...) to indicate
Determines the function parameter table. The ellipsis suspends the type check mechanism. Its appearance tells the compiler that when a function is called, there can be 0 or more instances.
Parameter, and the real parameter type location, two forms: void Foo (para_list,...) void Foo (...);
For example: int printf (const char *...)
Default real parameters: function declaration can specify the default real parameters for all or some parameters. Before any default real parameters of the Left parameter are provided, the rightmost parameter is used.
Default arguments must be provided for parameters not initialized. This is because the arguments for function calls are parsed by location.
Int ff (int A, int B, int C = 0)
Re-Declare: int ff (int A, int B = 0, int C)
Pointer: A reference must be initialized to point to an object. Once initialized, it cannot point to other objects.
It can point to a series of different objects and does not point to anything. An important usage of referencing parameters is that it allows us to effectively implement
When the current operator is overloaded, the usage is also intuitive.
Because the pointer can point to an object or no object, the function determines that the pointer actually points to a valid object
Therefore, when using a pointer as a parameter, we must first determine that the pointer is
No blank PTR = 0 or PTR = NULL
If you want to modify the pointer itself rather than the object referenced by the pointer, you can declare a parameter that is a pointer reference.
For example: void ptrswap (int * & V1, int * & V2 ){}
If a function wants to operate on real parameters, it must be passed by pointer or reference, and cannot be passed by value.
The visibility of objects defined in the for loop is limited to the for loop body. External access is invalid, and the while loop is the same.
Objects defined in condition in if (condition) are intended to be visible in the IF-related statements or statement blocks.
Subsequent accesses may cause compilation errors.
The ASC code is used to calculate the character, for example, 'A' is 97; 3 + 'A' = 100
C ++ automatically performs arithmetic conversion before computation to convert the data to the same type before computation. The conversion rule is that small types are always upgraded to large ones.
Type to prevent loss of precision.
&: The bitwise AND &: logic and;> the shift operation must have a left value. Otherwise, the return value is returned. For example, a> 3; A shifts three places to the right, and when output A is
Is the original value, to achieve the moving effect a = A> 3; can also achieve integer displacement, such as 5 <8; // 5 shifted to 8 places left
Comma expressions are a series of expressions separated by commas. These expressions are calculated from left to right and the result is the value of the rightmost expression.
The system provides a memory pool available for each program during program execution. This memory pool is called the idle storage of the program.
Zone or heap. Memory Allocation at runtime is called dynamic memory allocation.
The length of the byte of an object or type name. when applied to an array, the length of the byte of the entire array is returned.
The array identifier represents the address of the first element in the array. * IA is equivalent to IA [0], and * (IA + 1) is equivalent to IA [1].
A string (constant) contains an additional null ending character.
Non-const variables cannot be used to specify the dimension of an array.
If necessary, arithmetic and pointer values can also be implicitly converted to bool values, 0 or null pointers are converted to false, all other
All values are converted to true;
References are mainly used as parameters in the form of functions. Generally, class objects are passed to a parameter.
The const object address can only be assigned to the const Object Pointer, but the pointer to the const object can be assigned to a non-const object
And the non-const object cannot be changed through the const pointer.
Int * p = 0; NULL pointer
A string is stored in a character array and is usually manipulated by a char * pointer.
Anyone who does not know whether the pointer has a value should test the pointer before performing operations on the pointer.
If we only need to hold the address value (maybe compare an address with an address), the actual type of the pointer is not heavy.
The. c ++ provides a special pointer to support this requirement: a null pointer (void *), which can be used by any data pointer type
Address value assignment. You cannot operate on objects pointed to by null type pointers.
Pointer: for clarity, it is best to write int * X instead of int * X;
Int * X, Y; X is a pointer, while y is not
Right Value: read value left value: Location Value
Before a character, add L to indicate a wide character, such as l'a'. A wide character constant is used to support Character Set combination in some languages, such as Chinese.
An integer literal constant can be written in decimal, octal, and hexadecimal notation, but this does not change the bitwise sequence of the integer.
The string type supports accessing a single character through the subscript operator.
Judge whether the string ends: * STR ++; true if the string is not ended; false if the string is ended
While (* STR ++) cout <* STR; finally, the STR Pointer Points to the next address of the string. To use it correctly, you need to return it! (Parameter
Test strcpy)
If the pointer is null, STR = 0
20 023,0x14, add L after the integer literal constant, and specify it as a long integer. Add u to specify it as an unsigned number.
An iterator is a class object that supports pointer type abstraction.
Generally, when two or more functions repeat the same code, the code is extracted to form an independent function.
Shared, and later, if you need to change these implementations, you only need to change once.
Function calls are much more costly than direct access to memory. inline functions are expanded at their call points and are defined in class definitions.
The function is automatically regarded as an restrained function.
Int * pint = new int (12); // assign a pointer to an integer with the initial value 12 Delete pint;
Int * Pia = new int [4]; // assign an array of four integer elements to delete [] PIA;
In C ++, pointers are mainly used to manage and operate dynamically allocated memory.
Prevent a header file from being contained multiple times:
# Ifndef bookstore_h
# Define bookstore_h
Bookstore. H Content
# Endif
# Ifdef # endif is used in the program to determine whether a Preprocessor variable has been defined.
------------------------------------------------------------------
File input and output: # include <fstream>
Ofstream OUTFILE ("out_file ")
Ifstream infile ("in_file ")
Infile>;
OUTFILE <;
Arrays cannot be directly copied, for example, A = B. arrays do not know their own length.