Summary of basic knowledge of C++ entry (2022 finishing)

1. Basic knowledge of C++ entry What is C++?

In 1982, Dr. Bjarne Stroustrup introduced and expanded the concept of object-oriented on the basis of C language, and invented a new programming language. In order to express the relationship between the language and the C language, it is named C++. Therefore: C++ is based on the C language, it can not only carry out the procedural programming of the C language, but also can carry out the object-based programming characterized by abstract data types, and can also carry out the object-oriented programming.

The basic knowledge of C++ entry PDF version, C++ improvement tutorial, C++ e-books can be obtained as follows

Pay attention to the WeChat public account: "C and C plus" Reply to the keyword: "C++" to receive

Second, the basic knowledge of C++ entry look at the historical version of C++

  • C with classes classes and derived classes, public and private members, class construction and destructor, friends, inline functions, assignment operator overloading, etc.

  • C++1.0 adds the concept of virtual functions, overloading of functions and operators, references, constants, etc.

  • C++2.0 more perfect support for object-oriented, new protected members, multiple inheritance, initialization of objects, abstract classes, static members and const member functions

  • C++3.0 is further improved by introducing templates to solve the ambiguity problem caused by multiple inheritance and the processing of corresponding construction and destruction

  • The first version of the C++98 C++ standard, supported by most compilers, has been recognized by the International Organization for Standardization (ISO) and the American Standardization Association, rewritten the C++ standard library in a template manner, and introduced STL (Standard Template Library)

  • C++03 The second version of the C++ standard, the language features have not changed much, mainly: fix errors, reduce diversity

  • The C++05 C++ Standards Committee released a Technical Report (TR1), officially renamed C++0x, that is: planned to be released sometime in the first decade of this century

  • C++11 adds many features that make C++ more like a new language, such as: regular expressions, range-based for loops, auto keyword, new containers, list initialization, standard threading library, etc.

  • The extension of C++14 to C++11 is mainly to fix the vulnerabilities and improvements in C++11, such as: generic lambda expressions, auto return value type deduction, binary literal constants, etc.

  • C++17 has made some minor improvements on C++11, adding 19 new features, such as: optional text information for static_assert(), Fold expressions for variable templates, if and switch statements initializers etc.

Three, C++ basic knowledge keywords

There are a total of 63 keywords in C++:

The circled ones are the keywords of the C language.这里要注意了:false和true并不是C语言的关键字。

Fourth, the C++ namespace of the C++ entry foundation

In C/C++, variables, functions and classes exist in large numbers, and the names of these variables, functions and classes will be applied to the global scope, which may lead to many naming conflicts.

The purpose of using namespaces is to localize identifiers and names to avoid naming conflicts or name pollution. The namespace keyword appears to address this problem.

To define a namespace, you need to use the namespace keyword, followed by the name of the namespace, and then a pair of {}, where {} is the name

members of the space.

Note: A namespace defines a new scope, and everything in the namespace is limited to that namespace

1. Common definition of namespace

2. Namespaces can be nested

3. Multiple namespaces with the same name are allowed in the same project, and the compiler will eventually synthesize them into the same namespace.

it will be merged with the xjt namespace above

Five, the use of C++ entry basic namespace

Obviously, it is impossible to print printf directly, because you call the address of printf like this, so this result will appear. The positive calling methods are the following three.

1. Add namespace name and scope qualifier

The symbol "::" is called a scope qualifier in C++, and we can access the corresponding members in the namespace through "namespace name::namespace member"

2. Introduce using using namespace namespace name

But there are some drawbacks in this method. If we define a variable named printf in the namespace, then if we introduce the namespace xjt later, it will cause naming pollution.

To solve this problem, a third introduction method has emerged.

3. Use using to introduce members in the namespace

This approach prevents naming pollution, since it only introduces part of it.

6. Input and output of basic knowledge of C++ entry

There are standard input and output functions scanf and printf in C language, while in C++ there are cin standard input and cout standard output. To use the scanf and printf functions in the C language, the header file stdio.h needs to be included. To use cin and cout in C++, you need to include the header file iostream and the std standard namespace.

The input and output method of C++ is more convenient than the C language, because the input and output of C++ does not need to control the format, for example: the integer type is %d, and the character type is %c.

Note: endl, the l in this is not the Arabic numeral 1, but the l of 26 English letters, which is equivalent to a newline.

Here we should also pay attention to the characteristics of cin. It is similar to gets in C language. Gets stops when it encounters a newline, while cin uses a space, tab or newline as a separator, so enter hello world here. are separated by spaces.

Here I input hello world, but because there is a space when inputting, the content after that will not be read, so hello is stored in arr.

7. Basic knowledge of C++ entry - default parameters

A default parameter is when a function is declared or defined to specify a default value for a function's parameters. When calling the function, the
default value is used if no arguments are specified, otherwise the specified arguments are used.

1. All default

All default parameters, that is, all formal parameters of the function are set to default parameters.

2. Semi-default parameters

Notice: 

  • Semi-default parameters must be given sequentially from right to left, and cannot be given at intervals.

  • Default parameters cannot appear in both function declaration and definition

Because: if the declaration and the definition occur at the same time, and the two places happen to provide different values, the compiler cannot determine which default value to use.

  • The default value must be a constant or a global variable.

Eight, C++ basics - C++ function overloading

1. Function overloading

Function overloading is a special case of functions. C++ allows several functions of the same name with similar functions to be declared in the same scope . The formal parameter lists (number or type or order of parameters) of these functions with the same name must be different . Implementing similar functions with different data types

Note: If only the return value is different and everything else is the same, it does not constitute function overloading.

2. The principle of C++ function overloading

Why does C++ support function overloading, but C language doesn't?

Here we are going to review the previous knowledge. Before running to the executable file, we have to go through: precompile, compile, assemble, link these stages

In fact, the problem lies in the assembly stage after compilation, because C++ and C languages ​​are slightly different here. Let's take a look:

After compiling with C language compiler

After compiling with C++ compiler

Summarize:

  • In fact, in the final analysis, it is because the C compiler and the C++ compiler decorate function names differently. The modification rules under gcc are: [_Z + function length + function name +
    type first letter].

  • This actually tells us why the return type of the function is different and does not constitute function overloading, because the decoration rules are not affected by the return value.

3、external “C”

Sometimes in a C++ project, it may be necessary to compile some functions according to the C style, adding extern "C" before the function, which means to tell the compiler,

This function is compiled according to C language rules. For example: tcmalloc is a project implemented by google in C++, which provides tcmallc() and tcfree

Two interfaces are used, but if it is a C project, it cannot be used, so he uses extern "C" to solve it.

Nine, the basics of C++ entry - reference

1. Quote

The reference is not to define a new variable, but to take an alias for the existing variable . The compiler will not open up memory space for the reference variable, it shares the same memory space with
the variable it references .

type & reference variable name (object name) = reference entity;

Note: The reference type must be the same type as the reference entity

2. Features of reference

  • References must be initialized when they are defined

  • A variable can have multiple references

  • Once a reference refers to an entity, it cannot refer to another entity

But the actual effect is that the value of c is indeed assigned to b, and because b is a reference to a, the value of a becomes 20.

3. Often quoted

As mentioned above, the reference type must be the same type as the reference entity. But just the same type does not guarantee that the reference can be successful. Here we also need to pay attention to the question of whether it can be modified.

Here a, b, d are all constants, and constants cannot be modified, but if you use int&ra to refer to a, the referenced a can be modified, so there will be problems.
Let's look at this piece of code:

Is this quote correct? To understand this problem, we must first understand the problem of hermit type promotion. Here, there is a hermit type promotion from int to double, and during the promotion process, the system will create a constant area to store the result of type a promotion. So here, this code is wrong at first glance, because a is stored in the constant area when your hermit type is promoted, and the constant area cannot be modified, and you use double&ra to refer to it, the ra reference can be modified.

Adding a const can solve this problem.

Note: It is not possible to refer to an unmodifiable quantity as a readable and writable quantity, but the reverse is possible, and it is possible to refer to a readable and writable quantity as a readable quantity.

4. Reference usage scenarios

  • reference as parameter

    Remember the exchange function in the C language. When learning the C language, the exchange function is often used to illustrate the difference between pass-by-value and pass-by-reference. Now that we have learned about references, we can use pointers as parameters. Because here a and b are references to the incoming arguments, we swap the values ​​of a and b, which is equivalent to exchanging the two incoming arguments.

  • reference as return value

    Of course, references can also be used as return values, but we must pay special attention to the fact that the data we return cannot be ordinary local variables created inside the function, because ordinary local variables defined inside the function will be destroyed with the end of the function call. The data we return must be statically modified or dynamically created or global variables and other data that will not be destroyed with the end of the function call.

    Consequences of not adding static

Are you wondering why it prints 7 instead of 2?

This is even more strange, why add a printf in the middle to print random values?
Let's take a look at the analysis:

Why does the random value appear? Because the variable you define in the function is a temporary variable, and the function will be destroyed when it exits the function. At this time, it randomly points to a space in the memory . Therefore, it is better to add static to the variables defined in the function when the reference is used as the return value of the function.

At this point do you think you really understand this code?

Maybe you will be curious? Why is it 3 here? Let's look at the analysis

In fact, if you change the way of writing, the result here will be changed to 7. The reason is also very simple, which is the reason mentioned in the picture above.

Note: If the function returns out of the function scope and the returned object has not been returned to the system, you can use the reference to return; if it has been returned to the system, you must use the return by value.
This sentence says the following example:

Do you feel that this pass-by-reference return is weird to use, let's analyze how it is returned.

Summarize:
传值的过程中会产生一个拷贝,而传引用的过程中不会,其实在做函数参数时也具有这个特点。

5. Difference between reference and pointer

In terms of syntax, a reference is an alias, which has no independent space and shares the same space with its referencing entity.

There is actually space in the underlying implementation, because references are implemented as pointers.

Let's take a look at the assembly code comparison of references and pointers

Difference between reference and pointer

  • References must be initialized when they are defined, pointers are not required.

  • After a reference refers to an entity when it is initialized, it cannot refer to other entities, and a pointer can point to any entity of the same type at any time.

  • There are no NULL references, but there are NULL pointers.

  • The meaning in sizeof is different: the result of the reference is the size of the reference type, but the pointer is always the number of bytes occupied by the address space (4 bytes on a 32-bit platform).

  • The self-increment operation of the reference is equivalent to increasing the entity by 1, and the self-increment operation of the pointer is that the pointer is offset by the size of a type.

  • There are multiple levels of pointers, but no multiple levels of references.

  • Entities are accessed differently, pointers need to be dereferenced explicitly, and references are handled by the compiler itself.

  • References are relatively safer to use than pointers.

10. Basic knowledge of C++ entry - inline functions

1. Concept

A function decorated with inline is called an inline function. When compiling, the C++ compiler will expand it at the place where the inline function is called , without the overhead of function stacking,
and the inline function improves the efficiency of program operation. (When you see the bold part, your friends will definitely think, is this very similar to the macro in the c language?)

If you add the inline keyword before the above function to change it to an inline function, the compiler will replace the function call with the function body during compilation

2. Features

  • Inline is a way of exchanging space for time, eliminating the overhead of calling functions. So long code/recursive functions are not suitable to use as inline functions.

  • Inline is just a suggestion for the compiler, and the compiler will automatically optimize it. If the body code of the function defined as inline is relatively long/recursive, etc., the compiler will ignore the inline when optimizing.

  • Inline does not recommend the separation of declarations and definitions, separation will lead to link errors. Because the inline is expanded, there is no function address, and the link will not be found.

What are the techniques for c++ to replace macros

  • Replace constant definition with const

  • Replace function definitions with inline functions

Eleven, auto keyword (C++11)

In the early days of C/C++, the meaning of auto was: a variable decorated with auto is a local variable with automatic storage, but unfortunately no one has ever used it.

In C++11, the standard committee gave auto a new meaning: auto is no longer a storage type indicator, but as a new type indicator to instruct the compiler that variables declared by auto must be compiled by the compiler. derived over time. You may not understand just by reading this sentence. Let's give a few examples.

#include<iostream>

using namespace std;

int TestAuto()

{

return 10;

}

int main()

{

int a = 10;

auto b = a;

auto c = 'a';

auto d = TestAuto();



cout << typeid(b).name() << endl; //这个地方要学到后面类的时候才可以解释,这里打印出的是类型名

cout << typeid(c).name() << endl;

cout << typeid(d).name() << endl;



cout << a << endl;

cout << b<< endl;

cout << c << endl;

cout << d << endl;



//auto e; 无法通过编译,使用auto定义变量时必须对其进行初始化

return 0;

}

Note: When using auto to define a variable, it must be initialized. During the compilation phase, the compiler needs to deduce the actual type of auto according to the initialization expression. Therefore, auto is not a "type" declaration, but a "placeholder" when a type is declared. The compiler will replace auto with the
actual type of the variable at compile time.

1. Rules for the use of auto

  • auto is used in conjunction with pointers and references

When declaring a pointer type with auto, there is no difference between auto and auto*, but when declaring a reference type with auto, you must add &

Note: When declaring a reference with auto, you must add &, otherwise, it will just create an ordinary variable of the same type as the entity, but change its name.

  • Defining multiple variables on the same line

When declaring multiple variables on the same line, these variables must be of the same type, otherwise the compiler will report an error, because the compiler actually only
deduces the first type, and then defines other variables with the deduced type.

2. Scenarios that auto cannot deduce

  • auto as a function parameter

  • auto cannot be used directly to declare an array

In order to avoid confusion with auto in C++98, C++11 only retains the use of auto as a type indicator
. The most common advantage of auto in practice is the new style provided by C++11, which will be discussed later. For loops, lambda expressions, etc. can be used together.

12. Basic knowledge of C++ entry range-based for loop (C++11)

1. The syntax of range for

In C++98, if you want to traverse an array, you can do it as follows:

For a ranged collection, it is redundant and sometimes error-prone for the programmer to specify the range of the loop. So in C++11

A range-based for loop was introduced. The parentheses after the for loop are divided into two parts by the colon ":": the first part is the variable in the range used for iteration, and the second part represents the range to be iterated.

Note that it cannot be written as auto, otherwise the original array cannot be changed

correct spelling

Note: Similar to ordinary loops, you can use continue to end the current loop, and you can also use break to jump out of the entire loop.

2. Conditions of use of scope for

  • The range of the for loop iteration must be deterministic

For an array, it is the range of the first element and the last element in the array; for a class, the begin and end
methods should be provided, and begin and end are the range of the for loop iteration.

Note: The following code is problematic because the scope of the for is indeterminate

  • The iterable object implements the operations of ++ and ==.

About the iterator, I will talk about it later, but now you can understand it.

Thirteen, C++ entry foundation - pointer null value nullptr

1. Pointer null value in C++98

In good C/C++ programming practice, when declaring a variable, it is better to give the variable an appropriate initial value, otherwise unpredictable errors may occur. For example, for uninitialized pointers, if a pointer does not have a legal pointer, we basically initialize it as follows:

NULL is actually a macro. You can see the following code in the traditional C header file (stddef.h):

As you can see, NULL may be defined as a literal constant 0, or as a constant with an untyped pointer (void*). No matter what definition you take, you will inevitably encounter some troubles when using pointers with null values, such as:

The original intention of the program is to call the pointer version of the Fun(int* p) function through Fun(NULL), but since NULL is defined as 0, Fun(NULL) finally calls the Fun(int p) function.

Note: In C++98, the literal constant 0 can be either an integer number or an untyped pointer (void*) constant, but the compiler treats it as an integer constant by default, if To use it as a pointer, it must be cast.

2. Pointer null value in C++11

For issues in C++98, C++11 introduced the keyword nullptr.

When using nullptr to represent pointer null, no header file needs to be included because nullptr was introduced as a keyword in C++11.

In C++11, sizeof(nullptr) and sizeof((void*)0) occupy the same number of bytes, and both have a size of 4.

finally

The basic knowledge of C++ entry PDF version, C++ improvement tutorial, C++ e-books can be obtained as follows

Pay attention to the WeChat public account: "C and C plus" Reply to the keyword: "C++" to receive

Guess you like

Origin blog.csdn.net/weixin_55305220/article/details/123685978