The latest introduction tutorial of c + + basic knowledge in the whole network 2021YYDS!

Keywords: C C++

1, Introduction to C + + Basics

C + + is the inheritance of C language. It can not only carry out procedural programming of C language, object-based programming characterized by abstract data types, but also object-oriented programming characterized by inheritance and polymorphism. While C + + is good at object-oriented programming, it can also carry out process based programming. Therefore, C + + can adapt to the problem scale.

  C++ related complete information has been sorted out, and we need to pay attention to WeChat official account "C and C plus" reply to "88" can receive!

C + + not only has the practical characteristics of efficient computer operation, but also aims to improve the programming quality of large-scale programs and the problem description ability of programming language.

In C + +, class is a tool to support data encapsulation, and object is the implementation of data encapsulation. C + + supports data encapsulation and data hiding by establishing user-defined classes.

  In object-oriented programming, data and functions that legally operate on the data are encapsulated as the definition of a class. Object is described as a variable with a given class. The object of each given class contains several private members, public members and protected members specified by this class. Once a well-defined class is established, it can be regarded as a fully encapsulated entity and can be used as a whole unit. The actual internal work of the class is hidden. Users using well-defined classes don't need to know how the class works, just know how to use it.

2, Integrated development environment (IDE)

The relevant information has been sorted out, and WeChat's official account of "C and C plus" can be recalled to "88".

Writing programs requires tools, and the code needs different colors, called code highlighting. There are generally two tools - text editor and IDE. The text editor only provides code highlighting, and there are few tools, so the download size is relatively small. Usually Notepad + +, EMACS, Vim, sublime Text2, Xcode, etc. However, the functions of IDE are comprehensive. For developers, IDE is of great help to development.

CLion

Visual Studio (Visual C++)

C++ Builder

Code::Blocks -- an open source, full-featured cross platform C/C + + integrated development environment.

Wait, wait

The above is one IDE, and the most commonly used one is CLion.

3, Basic grammar

Input and output, although C and C + + are very similar, there are still slight differences

C + + style

The input and output of C + + is relatively simple, but some functions will be missing, so c + + also supports the input and output of C language

example:

#include <iostream>
using namespace std;
int main(){
    int aNum;
    cin >> aNum;
    cout << "aNum:" << aNum << endl;
    return 0;
}

Do you remember the #include < iostream > in the first line of the program? This iostream is for cin and cout. Of course, there are other functions. They are relatively advanced, so they are not mentioned here 🙂, Line 4 defines an integer variable aNum, which is explained below. Line 5, cin is the input identifier, > > is the input stream symbol, cout is the output identifier, and < < is the output stream symbol. Easy

  • Object - the behavior of an object that has a state. An object is an instance of a class.
  • Class - a class can be defined as a template for the behavior and state of an object.
  • Methods - basically, a method represents a behavior, and a class can contain multiple methods.
  • variable

1. Notes

//Single line note
/*
multiline comment
multiline comment
*/

2. Keywords

  3. Identifier

An identifier is the name used to identify a variable, function, class, module, or any other user-defined item. An identifier is underlined with the letters A-Z or A-Z_ Start with zero or more letters, underscores, and numbers (0-9).

Punctuation characters such as @, & and% are not allowed in identifiers. C + + is a case sensitive programming language.

4, Data type



1. The first C + + program

  2. Basic data type

Seven basic C + + data types: bool, char, int, float, double, void, wchar_t

Type modifiers: signed, unsigned, short, long

Note: some basic types can be decorated with one or more type modifiers. For example, signed short int is abbreviated as short, and signed long int is abbreviated as long.

3. Space occupied by data types in different systems

  This is related to the machine, operating system and compiler. For example, under the 32 bits operating system and VC + + compiler, the int type takes up 4 bytes; And 2 bytes under tuborC.

reason:

c/c + + specifies that the int word length is the same as the machine word length

The operating system word length may not be the same as the machine word length

The compiler defines the int word length based on the operating system word length

4. typedef declaration

5. Enumeration type

A derived data type in C + +, which is a collection of user-defined enumeration constants; Enumeration element is an integer type. Enumeration type can be implicitly converted to int type, and int type cannot be implicitly converted to enumeration type.

If the enumeration is not initialized, that is, when "= integer constant" is omitted, it starts from the first identifier;

By default, the value of the first name is 0, the value of the second name is 1, the value of the third name is 2, and so on. However, you can also assign a special value to the name by adding an initial value.

For example:

6. Constants and symbols

(1) Integer constant

Integer constants can be divided into signed integer constants and unsigned integer constants

Octal: starts with 0, that is, 0 is used as the prefix of octal numbers. Each value range is 0 ~ 7. Octal numbers are usually unsigned numbers.

For example, 016, 0101 and 0128 are legal octal numbers
Hexadecimal: starts with 0x or 0x, its digital value range is 0 ~ 9, and a ~ f or a ~ F

For example, 0X2A1, 0XC5 and 0xfff are legal hexadecimal numbers

(2) Real constant

Decimal representation: it consists of integer part and decimal part. Each value range of integer part and decimal part is 0 ~ 9, such as 0.0, 3.25, 0.00596 and 2.0
Exponential representation: the exponential part starts with the symbol "e" or "e", but must be an integer, and there must be a number on both sides of the symbol "e" or "e", such as 1.2e20 and -3.4e-2

(3) Character constant

Character constants are characters enclosed in single quotes, such as: 'a' and '?' Are legal character constants. The ASCII value of character 'a' is 97, the ASCII value of character 'a' is 41, and the character '?' The ASCII value of is 63

Escape character is a special character constant. When used, the string '' represents the beginning of escape, and the following different characters represent the escape characters. The escape character table is as follows:

  (4) String constant

Is a sequence of zero or more characters enclosed in a pair of double quotation marks, such as "welcome to our school" and "hello world". '' can represent an empty string.

The character constant 'A' is different from the string constant 'A'. The string constant 'A' is composed of two characters' A 'and' \ 0 '. The string length is 2. The string constant' A 'is only one character and has no length.

(5) Other constants

  • Boolean constant: there are only two Boolean constants. One is true, which means true; The other is false, which means false.
  • Enumeration constant: the members defined in enumeration data are also constants, which will be described later.
  • Macro definition constants: some values defined through #define macros are also constants. For example: define PI3.1415. Where PI is a constant.

7. Variable

A variable is simply the name of the storage area that the program can operate on. Each variable in C + + has a specified type, which determines the size and layout of variable storage. The values within this range can be stored in memory, and operators can be applied to variables.

(1) Identifier: a symbol used to identify constants, variables, statement labels and user-defined function names in C + + programs.
Identifier naming rules:

  • It is composed of letters, numbers and underscores, and cannot start with a number.
  • Uppercase and lowercase letters represent different meanings.
  • Cannot have the same name as a keyword
  • Try to "see the name and know the meaning", which should be bound by certain rules.
  • Illegal identifier: 6A, ABC *, case (reserved word)

c + + reserved keywords, as shown in the figure:

(2) Variable and variable description: variables must be defined or described before use. The general form of variable declaration is as follows: [modifier] type variable name identifier;

Type is the specifier of variable type, which describes the data type of variable. The modification master is optional and can not be changed.

  (3) Integer variables: integer variables can be divided into short, integer and long integers. Variable type specifiers are short, int and long respectively. It can also be divided into the following 6 types according to whether there are symbols.

  • Integer [signed] int
  • Unsigned integer unsigned [int]
  • Signed short [signed] short [int]
  • unsigned short [int]
  • Signed long [signed] long [int]
  • unsigned long [int]

  (4) Real variables: also known as floating-point variables, variables can be divided into single precision (float), double precision (double) and long double precision (long double).

(5) Variable assignment: the variable value changes dynamically, and assignment operation is required for each change. The form of variable assignment is as follows: variable name identifier = expression, for example:

  (6) Variable initial value assignment: data can be assigned to variables when variables are declared. This process is called variable initial value assignment. There are several cases of initial value assignment:

  • int x=5;: Indicates that x is defined as a signed basic integer variable with an initial value of 5
  • int x,y,z=6;: Indicates that x, y and Z are defined as signed basic integer variables, and Z has an initial value of 6
  • int x=3,y=3,z=3;: It means that x, y and Z are defined as signed basic integer variables, and the initial value given is 3

(7) Character variable:

  • A character type, that is, it can be output in character form or integer type:

  • It is allowed to perform arithmetic operation on character data. In this case, arithmetic operation is performed on their ASCII code values:  

(8) Scope of variable

Local variables: variables declared inside a function or a code block are called local variables. They can only be used by statements inside functions or code blocks.
Global variables: variables defined outside all functions (usually at the head of the program) are called global variables. The value of a global variable is valid throughout the life cycle of the program.

The names of local variables and global variables can be the same, but within a function, the value of the local variable overrides the value of the global variable.
When a local variable is defined, the system will not initialize it; When defining a global variable, the system will automatically initialize the value: int float double 0, char '\ 0', pointer NULL

8. Custom data type

(1) Structure

Structures can contain structures of different data types.

Defines the general form of the structure

Definition and initialization of structure variable name:

//Define the structure and declare the structure variable name
struct Structure type name
{
	Member type 1 member name 1;
	Member type 2 member name 2;
	... ...
	Member type n member name n;
}Variable name 1,Variable name 2,...Variable name n;
//Define the structure first
[struct] Structure type name variable name;
//Direct definition
struct 
{
	Member type 1 member name 1;
	Member type 2 member name 2;
	... ...
	Member type n member name n;
}Variable name 1,Variable name 2,...Variable name n;
struct  person
{
	int year;
	int age;
	string name;
}p1 = {2019,24,"heiren"}, p1 = { 2020,24,"heiren" };
struct  person
{
	int year;
	int age;
	string name;
};
struct person p1 = { 2019,24,"heiren" }, p1 = { 2020,24,"heiren" };
struct 
{
	int year;
	int age;
	string name;
}p1 = {2019,24,"heiren"}, p1 = { 2020,24,"heiren" };

Use of structure variables:

  • Structural variables of the same type can be assigned, but cannot be input or output
  • Member reference to structure variable: structure variable name. Member name
  • Reference format of pointer variable pointing to structure: pointer variable name - > member name;
    The definition, initialization and use of structure array are similar to structure variable and basic type array
struct person
{
	int year;
	int age;
	string name;
}p[2] ={ {2019,24,"heiren"}, { 2020,24,"heiren" }};//You can not specify the number of array elements
p[1].age;

There are three types of structure passing as a function: value passing, reference passing and pointer passing

Structure size and byte alignment
    In modern computers, the memory space is divided according to byte s. Theoretically, it seems that the access to any type of variable can start from any address, but the actual situation is that when accessing a specific type of variable, it is often accessed at a specific memory address, which requires various types of data to be arranged in space according to certain rules, Instead of sequential discharge one after another, this is alignment
    Why do I need byte alignment? Each hardware platform has a great difference in the processing of storage space. Some platforms can only access certain types of data from certain addresses. For example, some platforms start reading from the even address every time. If an int type (assumed to be a 32-bit system) is stored at the beginning of the even address, the 32bit data can be read out in one read cycle. If it is stored at the beginning of the odd address, it needs two read cycles, and the high and low bytes of the two read results can be pieced together to obtain the 32bit data.
Three concepts:

Self alignment value: the alignment value of the data type itself. The self alignment value of the structure or class is the largest value among its members. For example, the self alignment value of char type is 1 and the short type is 2;
Specified alignment value: the alignment value specified by the compiler or programmer. The specified alignment value of 32-bit MCU is 4 by default;
Valid alignment value: the smaller of the self alignment value and the specified alignment value.
Three criteria for byte alignment
The first address of a structure variable can be divided by the size of its valid alignment value
The total size of the structure is an integer multiple of the valid alignment value of the structure.
The offset of each member of the structure from the first address of the structure is an integer multiple of the valid alignment value.
You can use #pragma pack(n) to set variables in n-byte alignment

  (2) Common body (union)

Several different variables share memory space starting at the same address.

The member type can be either a basic data type or a construction data type.
When initializing a common body variable, only the first member can be assigned a value.
The length of memory occupied by common body variables is equal to the longest member length.
Only one member of a common body variable can function at a time. During assignment, members will overwrite each other, and the last assigned member will function.
definition:

union Community type name
{
    Member type 1 member name 1;
	Member type 2 member name 2;
	... ...
	Member type n member name n;
};

initialization

union data
{
	int i;
	float f;
	char c;
}x = {123};
union data
{
	float f;
	int i;
	char c;
};
data x = {12.3};
union 
{
	char c;
	int i;
	float f;
}x = {'y'};

quote

Community variable name.member name;
union data
{
	int i;
	float f;
	char c;
}x = {12};
int main()
{
	cout << x.i << " " << x.f << " " << x.c << endl;//12 1.68156e-44 
	x.c = 'c';
	cout << x.i <<" "<< x.f << " " << x.c << endl;//99 1.38729e-43 c
	return 0;
}

9. Data input and output

(1) Console screen

(2) Operation control

The header file iomanip.h defines some functions that control the output format of the stream. By default, integer numbers are output in decimal form, or they can be set as hexadecimal output through hex. The specific control functions of flow operation are as follows

 

5, Operators and expressions

1. Operator

(1) Arithmetic operators: arithmetic operations mainly refer to four commonly used operations: addition (+), subtraction (-), multiplication (*) and division (/). Arithmetic operators include monocular operators and binocular operators.

 

 

(2) Relational operator

Relational operators are mainly used to compare two objects, and the operation result is logical constant true or false.  

(3) Logical operator

A logical operator is an operation on two logical values: true and false. The result of the operation is still a logical value

 

(4) Assignment operator

(5) Bitwise operator

 

  (6) Shift operator

 

 

  (7) sizeof operator

(8) Conditional operator  

 

(9) Comma operator  

  (10) Operator priority

(11)   Operator overloading

The so-called overloading is to give new meaning. Function Overloading allows a function name to have multiple functions and perform different operations in different situations. Operator Overloading is also a truth. The same operator can have different functions.

Operator overloading is realized by function, which is essentially function overloading.
Allow overloaded operators

Overloaded operators are not allowed

Rules for overloaded operators:

  • You cannot define new operators by yourself. You can only overload existing C + + operators.
  • The number of operator operands cannot be changed.
  • The priority and associativity of operators cannot be changed
  • It shall be similar to the standard type operation function to avoid affecting readability.

General format:

Function type operator operator(parameter list)
{
	Function body
}
//Take chestnuts for example: define a vector class. Through operator overloading, you can operate with +.
class Vector3
{
public:
	Vector3();
	Vector3(double x,double y,double z);
public:
	Vector3 operator+(const Vector3 &A)const;
	void display()const;
private:
	double m_x;
	double m_y;
	double m_z;
};
Vector3::Vector3() :m_x(0.0), m_y(0.0), m_z(0.0) {}
Vector3::Vector3(double x, double y,double z) : m_x(x), m_y(y), m_z(z) {}
//Operator overloading 
Vector3 Vector3::operator+(const Vector3 &A) const
{
	Vector3 B;
	B.m_x = this->m_x + A.m_x;
	B.m_y = this->m_y + A.m_y;
	B.m_z = this->m_z + A.m_z;
	return B;
}
void  Vector3::display()const
{
	cout<<"(" << m_x << "," << m_y << "," << m_z << ")" << endl;
}

  There are two forms of operator overloading: overloaded function as a member of a class and overloaded function as a friend function of a class
According to different operator operands: binocular operator as class member function, monocular operator as class member function, binocular operator as class friend function, and monocular operator as class friend function.

When the binocular operator is used as a friend function, two parameters need to be specified.
Operator overloaded functions can be called explicitly as class member functions.

Overloading of common operators

  • Self increasing and self decreasing
  • Assignment Operators
  • Input \ output operator overloading

2. Expression

(1) Arithmetic expression

(2) Relational expression

(3) Conditional expression  

(4) Assignment expression

(5) Logical expression  

(6) Comma expression

6, Grammatical structure

1. while loop

  You can also pay attention to WeChat official account "C and C plus" reply to "ZXC", there are more surprises!

while(conditon)//0 is false, non-0 is true
{
	statement(s);
}

2. do... while loop

  3. Comparison between while and do... While

 

 4,for

for(init;conditon;increment)//0 is false, non-0 or nothing is written as true
{
	statement(s);
}
  • init is executed first and will only be executed once, or no statement can be written.
  • Then it will judge condition, execute the loop body if true, and skip the loop if false
  • After executing the loop body, execute increment and skip to 2
int array[5] = { 11, 22, 33, 44, 55 };
for (int x : array)
{
	cout << x << " ";
}
cout << endl;
// auto type is also in the new C++11 standard, which is used to automatically obtain the type of variable
for (auto x : array)
{
	cout << x << " ";
}
  • for each
    for enhanced loop in STL.
int a[4] = { 4,3,2,1 };
for each (int var in a)
{
	cout << var << " ";
}

5. Judgment structure

  • if
if(expr)
{
	statement;//If expr is true, the block of statements that will be executed 
}
if(expr)
{
   statement1;// If expr is true, the block of statements that will be executed
}
else
{
   statement2;// Statement to execute if expr is false
}
if(expr1)
{
   statement1;// If expr1 is true, the block of statements that will be executed
}
elseif(expr2)
{
   statement2;// If expr2 is true, the block of statements that will be executed
}
...
else
{
	statementElse;// Statement block executed when the above expressions are false
}
  • switch
switch(expression){
    case constant-expression  :
       statement(s);
       break; 
    case constant-expression  :
       statement(s);
       break; 
    // You can have any number of case statements
    default : // Optional
       statement(s);
}

The constant expression after each case must be different.
The order in which case statements and default statements appear has no effect on the execution results.
If there is no break after the case, no judgment will be made after the execution, and the next case statement will continue to be executed. Until I met brerak.
If there is no case after default, break can be omitted
Multiple case s can use a set of execution statements

char c = 'A';
	switch (c)
	{
	
	case 'A':
	case 'B':
	case 'C':
		cout << "Passed" << endl;
		break;
	default:
		cout << "fail," << endl;
	
	}

6. Cycle control

 

 

7. Loop nesting  

 

  8. Ternary operator

//If Exp1 is true, the value of Exp2 is calculated, and the result is the whole? The value of the expression. If Exp1 is false, the value of Exp3 is calculated, and the result is the whole? The value of the expression
Exp1 ? Exp2 : Exp3;

9. Preprocessing command

Preprocessor (delete program comments, execute preprocessing commands, etc.) – > compiler compiles source program

  • Macro definition: #define identifier string
  • The file contains: #include < filename > or #include "filename"
  • Conditional compilation
//If the identifier is #define defined, execute segment 1, otherwise execute segment 2
#ifdef identifier
	Segment 1
#else
	Segment 2
#endif
//If the identifier has not been #define defined, execute segment 1, otherwise execute segment 2
#ifndef identifier
	Segment 1
#else
	Segment 2
#endif
//If the expression is true, execute segment 1, otherwise execute segment 2
#if expression
	Segment 1
#else
	Segment 2
#endif

7, Arrays and pointers

1. One dimensional array

  Initialization form: data type array name [constant expression] = {initial value table};
Assign a value to an element of the array: array name [subscript] = value (subscript starts from 0)
Reference to array: array name [subscript]

  • When initializing an array, you can assign values to only some array elements
  • When assigning values to all element arrays, the length of the array can not be specified. The compiling system will determine the length of the array according to the number of initial values.
  • static array elements are not assigned initial values, and the system will automatically default to 0.

2. Two dimensional array

Define the form of one-dimensional array: data type data name [constant expression 1] [constant expression 2]
Initialization form: data type array name [constant expression 1] [constant expression 2] = {initial value table};
Assign a value to an element of the array: array name [row subscript] [column subscript] = value (subscript starts from 0)
Array reference: array name [row subscript] [column subscript]

Write all data in a curly bracket and assign values automatically in the order of the number of array elements in memory
Some elements can be assigned values, and the values of other elements are automatically taken as 0
When defining an initialization array, the length of the first dimension can be omitted, and the second dimension cannot be saved. The system will automatically confirm the number of rows

3. Character array

An array of char type can be regarded as a string when the last bit in the character array is' \ 0 '). The string class is defined in C + +, and the Cstring class is defined in Visual C + +.
Each character in the string occupies one byte, plus the last null character.

4. Pointer

A pointer is a variable whose value is the address of another variable. That is, the direct address of the memory location.
General form of declaration:

  • The data type is the data type of the variable pointed to by the pointer variable, * indicates that the subsequent variable is a pointer variable
data type *Pointer variable name;
int    *ip;    //Integer pointer 
double *dp;    //double pointer 
float  *fp;    //Floating point pointer 
char   *ch;    //Character pointer 

Initialization of pointer variables:

  • &Is the address operator, and the & variable name represents the address of the variable.
  • The data type of the variable must be consistent with the data type of the pointer variable.
  • For security reasons, pointers are sometimes initialized to NULL pointers (NULL or 0)
data type *Pointer variable name = &Variable name;
*Pointer variable name = &Variable name;
int a;
int *p = &a;
int *p2;
p2 = &a;

Reference to pointer variable:

  • &Take the address character * pointer operator (indirect operator), followed by the pointer variable, indicating the variable to which the pointer variable points.
  • &* the priority of is the same, and the combination method is from left to right. For ex amp le, & * P is equivalent to & (* P).
int x = 3;
int y;
int *p;
p = &x;
y = *p;//y = a

Pointer operation (address operation)

Arithmetic operation (moving pointer operation): addition and subtraction, self increase and self decrease.
The address obtained by p+n operation is p+n * sizeof (data type).
Two pointers of the same data type can perform addition and subtraction operations, which are generally used in array operations.
Relational operation: only when the pointer points to the same string of continuous storage units, such as arrays. Compare with 0 to determine whether it is a null pointer.
Assignment operation: the variable address is assigned to the pointer variable, the array element address is assigned to the pointer variable, and the pointer variable is assigned to other pointer variables.

int arr[10],len;
int *p1 = &arr[2],*p2 = &arr[5];
 len = p2-p1;//Number of elements between arr[2] and arr[5] 3

new and delete operators

  • new - allocate memory space for variables;
  • You can judge whether the space allocation is successful by judging the value of the pointer returned by new.
  • delete free space
Pointer variable = new data type(initial value);
delete Pointer variable;
delete[] Pointer variable;//Release addresses assigned to multiple variables
int *ip;
ip= new int(1);
delete ip;
int *ip;
 ip= new int[10];
 for (int i = 0; i < 10;i++)
 {
	 ip[i] = i;
 }
 delete[] ip;
int a[3][4] = {0};

5. Pointers and arrays

 

 

6. Array and new (dynamically create array)  

One dimensional array

int* arr1 = new int[2];//delete []arr1;
int* arr2 = new int[3]{ 1,2 };//delete []arr2

Two dimensional array

int m=2, n=3;
int** arr3 = new int*[2];//delete []arr3
for (int i = 0; i < 10; ++i)
{ 
	arr3[i] = new int[3]; // delete []arr3[i]
}
int* arr4 = new int[m*n];//Data is stored by row delete []arr3

7. Pointer and string

  • String array name: char ch[] = "heiren";char *p = ch;
  • String: char *p = "heiren";
  • Pointer assignment operation: char * p;p = "Heiren";
    Pointers and functions. Pointers can be used as parameters or return values of functions.

8. Pointer to function

 

  9. Quote

Reference can be regarded as an alias of data. This data can be found through this alias and the original name, which is similar to the shortcut in window.

The reference does not occupy memory space. It must be initialized at the same time as the definition, and no other data can be referenced.
When defining a reference, you need to add &, but you can't add &. Adding & when using means taking an address
Reference variable declaration: data type & reference name = variable name;

int a;
int &b = a;//a and b represent the same variables with the same address.

A reference can be used as a function parameter or as a function return value.

void swap(int &r1, int &r2) {
    int temp = r1;
    r1 = r2;
    r2 = temp;
}
int &add1(int &r) {
	r += 1;
	return r;
}
int main()
{
	int a = 12;
	int b = add1(a);
	cout << a << "   "<<b << endl;//13  13
	return 0;
}

When a reference is used as a function return value, a reference to local data cannot be returned because the local data will be destroyed after the function call is completed.
When the function runs on the stack and runs out of functions, the subsequent function calls will overwrite the local data of the previous function.

int &add1(int &r) {
	r += 1;
	int res = r;
	return res;
}
void test()
{
	int xx = 123;
	int yy = 66;
}
int main()
{
	int a = 12;
	int &b = add1(a);
	int &c = add1(a);
	test();//Function call to overwrite the local data of the previous function
	cout << a << "   "<<b <<" "<< c<<endl;//14   -858993460 -858993460
	return 0;
}

8, Functions

1. Function declaration and definition

  • Function type - the return value type of the function; Function name - must comply with C + + identifier naming rules, followed by a pair of parentheses; Function body - the subject part that implements the function; Argument list - in parentheses after the function name, used to pass or bring back values to the function.
  • In the function declaration, the parameter name can be omitted, and the parameter type and function type cannot be omitted.
  • The function declaration can be placed inside the calling function and before the calling statement; It can also be placed outside the main calling function. If it is before all the defined functions and the subsequent functions are defined in any order, each main calling function call does not need to be declared
  • When a function is defined before a function is called, the function declaration can be omitted.

The last two are summarized as follows: before calling a function, the program must know that there is such a function, and the declaration is to let the program know that there is such a thing in advance

Function declaration:

Function type function name(parameter list);
eg:
int max(int a,int b);//When declaring functions, a and B can be omitted
int max(int,int);
void show();

Function definition:

Function type function name(parameter list)
{
	Function body;
}
eg:
int max(int a,int b)
{
	int z;
	z = a>b?a:b;
	return z;
}

2. Function parameters and return values

  • Formal parameters: the parameters in parentheses after the function definition do not occupy memory before the function call.
  • Arguments: parameters in parentheses of function call, which can be constants, variables or expressions.

Formal parameters and arguments must have the same number, type and order. Function transfer methods: value transfer, pointer and reference

 

 

 

  3. Function call

  • Function can be used as a single statement. For the function with return value, the function call can be used as a part of the statement and the return value can be used to participate in the operation.
    Function call form: parameter passing – > function body execution – > return calling function
Function name(Argument list);
show();

  Nested calls to functions:

int a()
{
	return 666;
}
int b(int sum)
{
	return sum+a()
}
int main()
{
	cout<<b(222)<<endl;//888
	return 0;
}

  Recursive call of function: direct recursive call and indirect recursive call

  • A function directly or indirectly recursively calls the function itself, which is called the recursive call of the function
  • Recursion and regression: original problem = > subproblem solution of subproblem = > solution of original problem
//Direct recursive call: find the value of 1+...n
int total(int sum)
{
	if (sum == 1)
	{
		return 1;
	}
	return sum + total(sum - 1);
}
int main()
{
	cout << "total = " << total(10) << endl;//total = 55
	system("pause");
	return 0;
}
//Indirect recursive call
int f2();
int f1()
{
...
  f2()
}
int f2()
{
	f1();
}

4. Overloaded function

5. Inline function

9, String (string)

1. Definition and initialization of strings

//definition
string variable;
string str1;
//assignment
string str2 = "ShangHai";
string str3 = str2;
str3[3] = '2';//Assign a value to a character
//String array
string Array name[Constant expression]
string arr[3];

2. String handler

#include <iostream>
#include <algorithm>
#include <string>
string str;//Generate empty string
string s(str);//Generate a copy of the string str
string s(str, strbegin,strlen);//Take the part of the string str with the length of strlen starting from the subscript strbegin as the initial value of the string
string s(cstr, char_len);//With C_ Char before cstr of string type_ Len strings as the initial value of string s
string s(num ,c);//Generates a string of num c characters
string s(str, stridx);//Take the position from the beginning of the subscript stridx to the end of the string in the string str as the initial value of the string
size()and length();//Returns the number of characters of a string object
max_size();//Returns the maximum number of characters contained in a string object. If the number exceeds, length will be thrown_ Error exception
capacity();//The maximum number of characters a string object can contain before reallocating memory
>,>=,<,<=,==,!=//Support the comparison between string and C-string (such as STR < "hello"). When using >, > =, <, < = these operators, the characters are compared one by one in dictionary order according to the "current character characteristics", string ("aaaa") < string (AAAAA).    
compare();//It supports multi parameter processing and comparison with index value and length positioning substring. Returns an integer to represent the comparison result. The returned value has the following meanings: 0: equal 1: greater than - 1:
  
push_back() 
insert( size_type index, size_type count, CharT ch );//Insert count characters ch in the index position
insert( size_type index, const CharT* s );//Insert a constant string at the index position
insert( size_type index, const CharT* s, size_type n);//Insert constant string at index position
insert( size_type index, const basic_string& str );//Insert n characters in the constant string at the index position
insert( size_type index, const basic_string& str, size_type index_str, size_type n);//Insert the constant STR from the index position_ n characters from str
insert( size_type index, const basic_string& str,size_type index_str, size_type count = npos);//Insert the constant str from the index position_ str starts with count characters. The maximum value that count can represent is npos. This function does not constitute an overload. npos represents a constant and represents size_ The maximum value of T. If the find function of string does not find the specified character, it returns an npos
iterator insert( iterator pos, CharT ch );
iterator insert( const_iterator pos, CharT ch );
void insert( iterator pos, size_type n, CharT ch );//Insert n characters ch at the pos position pointed to by the iterator
iterator insert( const_iterator pos, size_type count, CharT ch );//Insert count characters ch at the pos position pointed to by the iterator
void insert( iterator pos, InputIt first, InputIt last );
iterator insert( const_iterator pos, InputIt first, InputIt last );
append() and + Operator
//Access string each string
string s1("yuanrui"); // Call constructor once
// Method 1: subscript method
for( int i = 0; i < s1.size() ; i++ )
     cout<<s1[i];
// Method 2: forward iterator
for( string::iterator iter = s1.begin();; iter < s1.end() ; iter++)
     cout<<*iter;
 // Method 3: reverse iterator
for(string::reverse_iterator riter = s1.rbegin(); ; riter < s1.rend() ; riter++)
     cout<<*riter;
 iterator erase(iterator p);//Delete the character indicated by p in the string
iterator erase(iterator first, iterator last);//Delete all characters on the iterator interval [first,last) in the string
string& erase(size_t pos = 0, size_t len = npos);//Delete the len characters from the index position pos in the string
void clear();//Delete all characters in the string
string& replace(size_t pos, size_t n, const char *s);//Replace the n characters of the current string starting from the pos index with the string s
string& replace(size_t pos, size_t n, size_t n1, char c); //Replace the n characters of the current string starting from the pos index with n1 characters c
string& replace(iterator i1, iterator i2, const char* s);//Replace the string in the current string [i1,i2) interval with the string s
//Tower () and toupper() functions or transform algorithm in STL
string s = "ABCDEFG";
for( int i = 0; i < s.size(); i++ )
     s[i] = tolower(s[i]);
transform(s.begin(),s.end(),s.begin(),::tolower);
size_t find (constchar* s, size_t pos = 0) const;//Starting from the pos index position of the current string, find the substring s and return the found position index, - 1 means that the substring cannot be found
size_t find (charc, size_t pos = 0) const;//Starting from the pos index position of the current string, find the character c and return the found position index, - 1 means that the character cannot be found
size_t rfind (constchar* s, size_t pos = npos) const;//Starting from the pos index position of the current string, reverse the search for the substring s and return the found position index, - 1 indicates that the substring cannot be found
size_t rfind (charc, size_t pos = npos) const;//Starting from the pos index position of the current string, reverse the search for the character c and return the found position index, - 1 indicates that the character cannot be found
size_tfind_first_of (const char* s, size_t pos = 0) const;//Starting from the pos index position of the current string, find the character of the substring s, and return the found position index, - 1 indicates that the character cannot be found
size_tfind_first_not_of (const char* s, size_t pos = 0) const;//Starting from the pos index position of the current string, find the first character not located in the substring s, and return the found position index, - 1 indicates that the character cannot be found
size_t find_last_of(const char* s, size_t pos = npos) const;//Starting from the pos index position of the current string, find the last character in the substring s, and return the found position index, - 1 indicates that no character can be found
size_tfind_last_not_of (const char* s, size_t pos = npos) const;//Starting from the pos index position of the current string, find the last character not located in the substring s, and return the found position index, - 1 indicates that the substring cannot be found
sort(s.begin(),s.end());
substr(pos,n);//The return string is n characters from the subscript pos
strtok()
char str[] = "I,am,a,student; hello world!";
const char *split = ",; !";
char *p2 = strtok(str,split);
while( p2 != NULL )
{
    cout<<p2<<endl;
    p2 = strtok(NULL,split);
}

10, Object oriented and class oriented

Object oriented overview

1. Class

Class is also a data type.

Class declaration:

class Class name
{
	public:
		Public data members ;
		public functions ;
	private:
		Private data member;
		Private member function;
	protected:
		Protect data members;
		Protect member functions;
};

  Definition of member function: in class, out of class, out of class inline function

//Out of class
 Return type class name:Member function name(parameter list)
{
	Function body;
}
//Inline functions: out of class
inline Return type class name:Member function name(parameter list)
{
	Function body;
}

2. Access rights of class members and encapsulation of classes

public, private and protected in C + + can only modify class members, not classes. Classes in C + + do not share private ownership
There is no restriction on access rights inside the class. You can access each other.
In the class defined by class in C + +, the default access permission of its members is private.

3. Object  

//1. Declare classes and define objects at the same time
class Class name
{
	Class body;
}Object name list;
//2. First declare the class and then define the object
 Class name object name(parameter list);//() may not be written when the parameter list is empty
//3. Define the object directly without class name
class 
{
	Class body;
}Object name list;
//4. Create objects on the heap
Person p(123, "yar");//Create object on stack
Person *pp = new Person(234,"yar");//Create objects on the heap

Note: you cannot initialize its data members while defining a class, because the class is not an entity, which is illegal, but can be compiled and run
Reference of object member: object name. Data member name or object name. Member function name (parameter list)

4. Constructor

  The constructor name must be the same as the class name

There are no return values and return types

The created object is called automatically, which does not need to be called by the user, and is only used once

Class does not define any constructor. The compilation system will automatically generate a default parameterless constructor for this class
Constructor definition

//1. Definition in class 2. Declaration in class, definition outside class
[Class name::]Constructor name(parameter list)
{
	Function body
}

create object

Class name object name(parameter list);//() may not be written when the parameter list is empty

Constructor with default parameters

class Person
{
public:
	Person(int = 0,string = "Zhang San");
	void show();
private:
	int age;
	string name;
};
Person::Person(int a, string s)
{
	cout<<a<<" "<<s<<endl;
	age = a;
	name = s;
}
void Person::show()
{
	cout << "age="<<age << endl;
	cout << "name=" <<name << endl;
}
int main()
{
     Person p; //0 sheets 3
	Person p2(12);//12 sheets three
	Person p3(123, "yar");//123 yar
	return 0;
}

Constructor with parameter initialization table

Class name::Constructor name(parameter list):Parameter initialization table
{
	Function body;
}
General form of parameter initialization list:
Parameter name 1(Initial value 1),Parameter name 2(Initial value 2),...,Parameter name n(initial value n)
class Person
{
public:
	Person(int = 0,string = "Zhang San");
	void show();
private:
	int age;
	string name;
};
Person::Person(int a, string s):age(a),name(s)
{
	cout << a << " " << s << endl;
}

Constructor overloading: the constructor name is the same, and the number and type of parameters are different.

  copy constructor

Class name::Class name(Class name&Object name)
{
	Function body;
}
class Person
{
public:
	Person(Person &p);//Declare copy constructor
	Person(int = 0,string = "Zhang San");
	void show();
private:
	int age;
	string name;
};
Person::Person(Person &p)//Define copy constructor
{
	cout << "copy constructor " << endl;
	age = 0;
	name = "ABC";
}
Person::Person(int a, string s):age(a),name(s)
{
	cout << a << " " << s << endl;
}
int main()
{
	Person p(123, "yar");
	Person p2(p);
	p2.show();
	return 0;
}
//output
123 yar
 copy constructor 
age=0
name=ABC

5. Destructor

  6. Object pointer

Declaration and use of object pointers

Class name *Object pointer name;
Object pointer = &Object name;
//Access object members
 Object pointer->Data member name
 Object pointer->Member function name(parameter list)
Person p(123, "yar");
Person* pp = &p;
Person* pp2 = new Person(234,"yar")
pp->show();

  Pointer to object member

Data member type *Pointer variable name = &Object name.Data member name;
Function type (Class name::*Pointer variable name)(parameter list);
Pointer variable name=&Class name::Member function name;
(Object name.*Pointer variable name)(parameter list);
Person p(123, "yar");
void(Person::*pfun)();
pfun = &Person::show;
(p.*pfun)();

this pointer
Each member function has a special pointer this, which always points to the object operated by the currently called member function

class Person
{
public:
	Person(int = 0,string = "Zhang San");
	void show();
private:
	int age;
	string name;
};
Person::Person(int a, string s):age(a),name(s)
{
	cout << a << " " << s << endl;
}
void Person::show()
{
	cout << "age="<<this->age << endl;
	cout << "name=" <<this->name << endl;
}

7. Static member

  You can also pay attention to WeChat official account "C and C plus" reply to "ZXC", there are more surprises!

Members starting with the keyword static are static members, which are shared by multiple classes.

  • static member variable belongs to a class, not a specific object
  • Static member functions can only access static data members in a class
    Static data member
//In class declaration, out of class definition
class xxx
{
	static Data type static data member name;
}
Data type class name::Static data member name=initial value
//visit
 Class name::Static data member name;
Object name.Static data member name;
Object pointer name->Static data member name;

Static member function

  8. Friends

With the help of friends, member functions in other classes and functions in the global scope can access the private members of the current class.
friend function

The friend function is not a member function of a class, so there is no this pointer, and the object must be passed through parameters.
The name of an object member cannot be directly referenced in a friend function. The member of the object can only be referenced through the object or object pointer passed in by the formal parameter.

//1. Declare a non member function as a friend function
class Person
{
public:
	Person(int = 0,string = "Zhang San");
	friend void show(Person *pper);//Declare show as a friend function
private:
	int age;
	string name;
};
Person::Person(int a, string s):age(a),name(s)
{
	cout << a << " " << s << endl;
}
void show(Person *pper)
{
	cout << "age="<< pper->age << endl;
	cout << "name=" << pper->name << endl;
}
int main()
{;
	Person *pp = new Person(234,"yar");
	show(pp);
	system("pause");
	return 0;
}
//2. Declare member functions of other classes as friend functions
//Member functions in person can access private member variables in MobilePhone
class MobilePhone;//Advance declaration
//Declare the Person class
class Person
{
public:
	Person(int = 0,string = "Zhang San");
	void show(MobilePhone *mp);
private:
	int age;
	string name;
};
//Declare the MobilePhone class
class MobilePhone
{
public:
	MobilePhone();
	friend void Person::show(MobilePhone *mp);
private:
	int year;
	int memory;
	string name;
};
MobilePhone::MobilePhone()
{
	year = 1;
	memory = 4;
	name = "iphone 6s";
}
Person::Person(int a, string s):age(a),name(s)
{
	cout << a << " " << s << endl;
}
void Person::show(MobilePhone *mp)
{
	cout << mp->year << "year  " << mp->memory << "G " << mp->name << endl;
}
int main()
{
	Person *pp = new Person(234,"yar");
	MobilePhone *mp = new MobilePhone;
	pp->show(mp);
	system("pause");
	return 0;
}

Friend class
When a class is a friend of another class, it is called a friend class.   All member functions of a friend class are friend members of another class.
Syntax form: friend [class] friend class name

  • Friend relationships between classes cannot be passed
  • The friend relationship between classes is one-way
  • Friend relationships cannot be inherited

11, Inheritance and derivation

1. Inherit

Inheritance is to create a new class based on an existing class. The existing class is called the base class or parent class, and the newly established class is called the derived class and child class; Derivation and inheritance are a concept from different angles. Inheritance is that the son inherits the father's industry, and derivation is that the father inherits the industry to his son.

A base class can derive multiple derived classes, and a derived class can inherit multiple base classes

Declaration of derived classes:

  Inheritance method:

The access properties of the public and protected members of the public base class remain unchanged, and the private members are not visible.
Private - public members and protected members of the base class become private members, which can only be accessed directly by member functions of derived classes, and private members are not visible.
Protected - the public and protected members of the base class become protected members, which can only be accessed directly by the member functions of the derived class, and the private members are not visible.

Using the using keyword, you can change the access rights of base class members in derived classes; Using can only modify the access permissions of public and protected members in the base class.

class Base
{
public:
	void show();
protected:
	int aa;
	double dd;
};
void Base::show(){
}
class Person:public Base
{
public:
	using Base::aa;//Change the protected member of the base class to public
	using Base::dd;//Change the protected member of the base class to public
private:
	using Base::show;//Change the public member of the base class to private
	string name;
};
int main()
{
	Person *p = new Person();
	p->aa = 12;
	p->dd = 12.3;
	p->show();//error
	delete p;
	return 0;
}

  Constructors and destructors of derived classes

  • Execute the constructor of the base class first, and then the constructor of the derived class
  • First execute the destructor of the derived class, and then execute the destructor of the base class.
  • Constructor of derived class: derived class name (total parameter list): base class name (base class parameter list), sub object name 1 (parameter list) {constructor body;}
class Base
{
public:
	Base(int, double);
	~Base();
private:
	int aa;
	double dd;
};
Base::Base(int a, double d) :aa(a), dd(d)
{
	cout << "Base Class Constructor!!!" << endl;
}
Base::~Base()
{
	cout << "Base Class Destructor!!!" << endl;
}
class Person:public Base
{
public:
	Person(int,double,string);
	~Person();
private:
	string name;
};
Person::Person(int a,double d,string str):Base(a,d),name(str)
{
	cout << "Person Class Constructor!!!" << endl;
}
Person::~Person()
{
	cout << "Person Class Destructor!!!" << endl;
}
int main()
{
	cout << "establish Person object..." << endl;
	Person *p = new Person(1,2,"yar");
	cout << "delete Person object...." << endl;
	delete p;
	system("pause");
	return 0;
}

2. Multiple inheritance

A derived class inherits the behavior of multiple base classes at the same time.

Multi inheritance is easy to make the code logic complex and confused, which has been controversial. It is rarely used in small and medium-sized projects. Later, Java, C#, PHP and so on simply cancelled multi inheritance.

General form of multiple inheritance derived class declaration:

Constructor for multiple inheritance derived classes:

  Ambiguity problem: multiple base classes have members with the same name, so the access is not unique.

  • 1. Class name: member name with the same name;
  • 2. A derived class defines a member with the same name and accesses the member with the same name of the derived class.

3. Virtual base class

c + + introduces a virtual base class so that when a derived class inherits an indirect common base class, only one member with the same name is retained.

The purpose of virtual inheritance is to make a class declare that it is willing to share its base class. The shared base class is called Virtual Base Class.
A member of a derived class with the same name takes precedence over a virtual base class
Declaration of virtual base class: class derived class name: base class name of virtual inheritance mode

class  A//virtual base class
{
protected:
	int a;
};
class B: virtual public A
{
protected:
	int b;
};
class C:virtual public A
{
protected:
	int c;
};
class D:public B,public C
{
protected:
	int d;
	void show()
	{
		b = 123;
		c = 23;
		a = 1;
	}
};

  If one of the classes in B or C defines a, there will be no ambiguity. A of the derived class has higher priority than a of the virtual base class.

If a is defined in both B and C, D's direct access to a will cause ambiguity.
Application: iostream, istream, ostream, base in c + +_ io

4. Upward transformation

For data type conversion, the compiler will directly throw away the decimal part (not round)

  A derived class can only be assigned to a base class (called an upward transformation in C + +): a derived class object can be assigned to a base class object, a derived class pointer can be assigned to a base class pointer, and a derived class reference can be assigned to a base class reference
The derived class object is assigned to the base class object, and the new members of the derived class are discarded; The derived class pointer is assigned to the base class pointer. It does not copy the members of the object or modify the data of the object itself, but only changes the pointer; The derived class reference is assigned to the base class reference, which is the same as that of the pointer
After the transformation, only the members inherited from the base class (including member variables and member functions) can be accessed through the objects, pointers and references of the base class, but the new members of the derived class cannot be accessed

5. Polymorphism

  Different objects can use the same function name to call functions with different contents.

  • Static polymorphism - when the program is compiled, the system determines which function to call, such as function overloading and static polymorphism
  • Dynamic polymorphism - dynamically determine which function to call during program operation, which is realized by virtual functions.

6. Virtual function

No specific operations are performed in the base class, and only a unified virtual function is provided for the derived class, which is declared as a virtual function.

  An important means to realize program polymorphism is to use the pointer of the base class object to access the function with the same name of the derived class object.

  • The function in the base class is declared as a virtual function, and the function with the same name in the derived class is automatically declared as a virtual function.
  • Declaration form: virtual function type function name (parameter list);
  • Constructors cannot be declared as virtual functions, destructors can be declared as virtual functions.
class  A
{
public:
	virtual void show()
	{
		cout << "A show" << endl;
	}
};
class B:  public A
{
public:
	void show()
	{
		cout << "B show" << endl;
	}
};
int main()
{
	
	B b;
	b.show();//B show
	A *pA = &b;
	pA->show();//B show if the show method is not declared as a virtual function with virtual, A show will be output here
	
	system("pause");
	return 0;
}

7. Pure virtual function

8. Abstract class  

  12, IO stream

  1. Stream classes and objects

Input stream - a stream from an input device to memory.
Output stream - the stream that flows out of the device from memory.
Memory buffer - used to store data in the stream.
Input / output process: keyboard input = "keyboard buffer = (carriage return trigger)" program input buffer = "> >" extract data
                        Output buffer = (buffer full or endl) "< <" sent to display
Input / output stream class:
iostream: ios ,istream,ostream,iostream
fstream: ifstream,ofstream,fstream
strstream: istrstream,ostrstream,strstream

  • istream is a stream class for input, and cin is the object of this class.
  • ostream is a stream class for output, and cout is the object of this class.
  • ifstream is a class used to read data from a file.
  • ofstream is a class used to write data to a file.
  • iostream is a class that can be used for both input and output.
  • fstream is a class that can read data from and write data to files.
  • istrstream input string class
  • ostrstream output string class
  • strstream input / output string stream class

  2. Standard input / output stream

The input / output stream Library (iostream) of C + + defines four standard stream objects: CIN (standard input stream - Keyboard), cout (standard output stream - screen), cerr (standard error stream - screen), and clog (standard error stream - screen)

cerr outputs information directly to the display without using buffer; The information output to the clog will be stored in the buffer first, and will not be output to the screen until the buffer is full or refreshed.
cout is the object of ostream class. The parameterless constructor and copy constructor of ostream class are private, so the object of ostream class cannot be defined.
When using > > to extract data, the system will skip white space characters such as spaces, tabs, line breaks, etc. So when you enter values for a set of variables, you can separate them.
If you enter a string, it also skips white space characters, and the string end flag \ 0 will be added at the end of the string.

int  x;
double y;
cin>>x>>y;
//Enter 22 66.0. Data can be separated by spaces, tabs, and carriage returns
char str[10];
cin>>str;//hei ren string contains only hei Hei \ 0

Member functions in the input stream

  • get functions: cin.get(), cin.get(ch) (non-zero value is returned successfully, otherwise 0 is returned), CIN. get (character array (or character pointer), number of characters n, termination character)

  •   Getline function: cin.getline (character array (or character pointer), number of characters n, termination flag character) read the character, know the termination character, or read n-1 characters, and assign it to the specified character array (or character pointer)

  • cin.peek() does not skip spaces and carriage returns in the input stream. When the input stream has ended, cin.peek() returns EOF.
  • ignore(int n =1, int delim = EOF)

  •   putback(char c), you can insert a character at the beginning of the input stream.

  Output stream object

  • Insert endl - output all data, insert line breaks, and empty the buffer
  • \n - output line wrap, do not empty buffer
  • Cout.put (parameter) outputs a single character (it can be a character or ASII code)

Format output
Flow operators defined in iomanip:

  • *It is not a part of the operator. The asterisk indicates that the operator is used without any operator. For example, by default, the integer is output in decimal form, which is equivalent to the dec operator

  Usage of stream operator: cout < < hex < < 12 < < "," < 24// c,18

setiosflags() operator
The setiosflags() operator is actually a library function. It takes some flags as parameters. These flags can be the following values defined in the iostream header file. Their meaning is the same as that of the operator with the same name.

  Multiple flags can be connected by the | operator, indicating that they are set at the same time. For example:

  If two conflicting flags are set at the same time, the result may be that neither flag works. The original flag should be cleared with resetiosflags

  Member functions in ostream class:

  The flags used in setf and unsetf functions are exactly the same as those used in setiosflags and resetiosflags.

13, File operation  

File - refers to the data set stored on external media. According to the data organization, files are divided into two types: ASCII file (text / character) and binary file (internal format / byte)

ASCII file output is still a binary file. The data form is the same. For numerical data, the output is different

1. File classes and objects

There are three classes in the C + + standard class library that can be used for file operations. They are collectively referred to as file stream classes. The three classes are:

ifstream: an input stream class used to read data from a file.
ofstream: output stream class, which is used to write human data to a file.
Fsstream: input / output stream class, which can be used to read data from and write human data to files.
File stream object definition:

  2. Open file

  Open function: void open(const char* szFileName, int mode);

ios::binary can be used in combination with other schema tags

Constructor of stream class
eg:ifstream::ifstream (const char* szFileName, int mode = ios::in, int); 

  3. File reading and writing

 

 

4. File pointer move operation

  • I fstream class and fsstream class have seekg member function, which can set the position of file read pointer;
  • ofstream class and fsstream class have seekp member functions, which can set the position of the file write pointer.
  • I fstream and fsstream classes also have tellg member functions, which can return the position of the file read pointer;
  • ofstream and fsstream classes also have tellp member functions, which can return the position of the file write pointer.

Function prototype

ostream & seekp (int offset, int mode);
istream & seekg (int offset, int mode);
//There are three mode s: ios::beg - offset (> = 0) bytes from the beginning to the back ios::cur - current forward (< = 0) / rear (> = 0) offset bytes ios::end - offset bytes from the end to the front (< = 0)
int tellg();
int tellp();
//The seekg function locates the file read pointer to the end of the file, and then the tellg function obtains the position of the file read pointer, which is the file length

  5. The difference between opening text files and binary files

On UNIX/Linux platforms, there is no difference between opening files in text or binary mode.
On UNIX/Linux platforms, text files take \ n (ASCII code 0x0a) as line feed symbols; On the Windows platform, text files use the concatenated \ r\n (\ r's ASCII code is 0x0d) as the newline symbol.
On Windows platform, if the file is opened in text mode, when reading the file, the system will convert all \ R \ nin the file into one character. If two consecutive bytes in the file are 0x0d0a, the system will discard the first 0x0D byte and only read 0x0a. When a file is written, the system converts \ n to \ r\n write.
It is always safest to open a file in binary mode.

14, Generics and templates

  • Generic programming is an algorithm that does not specify the type of data to be operated when it is implemented. It means that the algorithm can be applied to a variety of data types as long as it is implemented once. Its advantage lies in code reuse and reducing repeated code writing.
  • Templates are the basis of generics and the blueprint or formula for creating generic classes or functions

  1. Function template

General form of function template:

template<class T>or template<typename T>
Function type function name(parameter list)
{
	Function body;
}
template<class T1,class T2,...>//class can be replaced by typename
 Function type function name(parameter list)
{
	Function body;
}
//Take a chestnut
template<class T> T max(T a, T b)
{
	return a > b ? a : b;
}
int main()
{
	cout <<"max value is "<< max(12,34) << endl;//34
	cout << "max value is " << max(12.4, 13.6) << endl;//13.6
	cout << "max value is " << max(12.4, 13) << endl;//error there is no instance of function template "max" matching the parameter list. The parameter type is: (double, int)
	return 0;
}

  2. Class template

After declaring the class template, you can use type parameters for class member functions and member variables. In other words, the built-in types such as int, float and char can be replaced by type parameters.
General form of class template:

When a member function in a class is defined outside the class declaration, it must be defined as a function template with a template header. The definition form is as follows:

3. Use of templates

  4. The difference between typename and class

After c + + was introduced into the template, class was used to define the template parameter type. Later, in order to avoid confusion caused by the use of class declaration class and template, the keyword typename was introduced.

The keyword class and typename in the template definition syntax work exactly the same.
The difference is that typename has another function: using nested dependent name

class MyClass
{
public:
		typedef int LengthType;
		LengthType getLength() const
		{
			return this->length;
		}
		void setLength(LengthType length)
		{
			this->length = length;
		}
		
private:
	LengthType length;
};
template<class T>
void MyMethod(T myclass)
{
	//Tell the c + + compiler that the string after typename is a type name, not a member function or member variable
	typedef typename T::LengthType LengthType; //
	LengthType length = myclass.getLength();
	cout << "length = " <<length<< endl;
	
}
int main()
{
	MyClass my;
	my.setLength(666);
	MyMethod(my);//length = 666
	return 0;
}

15, Namespace and exception handling

1. Namespace

A namespace is actually a memory area named by the user. The user can specify a named space area as needed. Each namespace has a scope. Putting some global entities in the namespace is separated from other global entities.
General form of namespace definition:

  References to namespace members: namespace name:: namespace member name
Use namespace alias: namespace alias = namespace name
Format for declaring namespace members using using: using namespace name:: namespace member name;
Use using to declare all members of the namespace: using namespace namespace name;

After using declaration, when using the namespace member in the scope where the using statement is located, it does not need to be qualified with the namespace name.
All identifiers of the standard C + + library, including functions, classes, objects, and class templates, are defined in a namespace called std.
Nameless namespace, valid only within the scope of this file.

2. Exception handling

 

 

 

  16, STL

C + + Standard Template Library (STL) is the most successful example of generic programming. STL is a collection of templates for some common data structures and algorithms. It was developed under the auspices of Alex Stepanov and joined the C + + standard in 1998.

The core of C + + standard template library includes three components: container, algorithm and iterator

1. Container

Sequential container: variable length dynamic array Vector, double ended queue deque, bidirectional linked list
Associated containers: set, multliset, map, multimap

The elements in the associated container are sorted, so it has very good performance when searching.
Container adaptation: stack, queue, priority_queue
All containers have the following functions:

  Sequential container and associated container functions:

  Functions unique to sequential containers:

2. Iterator

An iterator is a data type that checks the elements in a container and traverses the elements. C + + tends to use iterators rather than subscript operations, because the standard library defines an iterator type for each standard container (such as vector), and only a few containers (such as vector) support subscript operations to access container elements. By definition, it can be divided into the following four types.

  • Forward iterator: container class name:: iterator iterator name;
  • Constant forward iterator: container class name:: const_iterator iterator name;
  • Reverse iterator: container class name:: reverse_iterator iterator name;
  • Constant reverse iterator: container class name:: const_reverse_iterator iterator name

3. Algorithm

STL provides algorithms that can be used in various containers (about 70 kinds), such as insertion, deletion, search, sorting, etc. The algorithm is the function template. The algorithm manipulates the elements in the container through iterators.
Most common algorithms in STL are defined in the header file algorithm. In addition, there are some algorithms in the header file numeric.
Many algorithms operate on an interval on the container (or the whole container), so two parameters are required, one is the iterator of the starting element of the interval, and the other is the iterator of the next element after the end element of the interval.
Will change the container it acts on. For example:

  • Copy: copy the contents of one container to another.
  • remove: deletes an element from the container.
  • random_shuffle: randomly shuffle the elements in the container.
  • fill: fills the container with a value.

Does not change the container it acts on. For example:

  • Find: find elements in the container.
  • count_if: count the number of elements that meet certain conditions in the container.
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()  {
   vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4); //1,2,3,4
	vector<int>::iterator p;
	p = find(v.begin(), v.end(), 3); //Find 3 in V. if it cannot be found, find returns v.end()
	if (p != v.end())
		cout << "1) " << *p << endl; //eureka
	p = find(v.begin(), v.end(), 9);
	if (p == v.end())
		cout << "not found " << endl; //Can't find

	p = find(v.begin() + 1, v.end() - 1, 4); //Find 4 in the two elements 2 and 3
	cout << "2) " << *p << endl; //Not found, pointing to the next element 4

	int arr[10] = { 10,20,30,40 };
	int * pp = find(arr, arr + 4, 20);
	if (pp == arr + 4)
		cout << "not found" << endl;
	else
		cout << "3) " << *pp << endl;
	return 0;

}

17, Finally

At the end of this article, if it can help you, welcome to praise and support!

  C++ related complete information has been sorted out, can pay attention to WeChat official account "C and C plus" reply "88" can receive!

 

Posted by Sk8Er_GuY on Wed, 29 Sep 2021 14:42:40 -0700