C + + Basics

Basic knowledge of C + + (I)

1. Foreword

πŸ‘‰πŸ‘‰ In 1979, C + + was born and sprouted. In 1983, it was officially renamed C + +, Benjani Strauss LUP (Bjarne Stroustrup). C + + can carry out both process oriented programming in C language and object-oriented programming (encapsulation, inheritance and polymorphism) in Java language. It is an intermediate language, between high-level language (Natural Language) and Low level language (machine language).

2. Compiler environment

πŸ‘‰πŸ‘‰MinGW (Minimalist GNU for Windows), which is a set of windows specific header files that can be used and released freely and imported and stored using GNU toolset. It allows local windows programs to be generated on GNU/Linux and windows platforms without the need for a third-party C runtime library. Although MinGW comes with Vim that supports the system clipboard, its use experience is much worse than GNU/Linux, so Dev-C + + should be used as the editor.

πŸ‘‰πŸ‘‰Dev-C++ It is a lightweight C/C + + integrated development environment (IDE) suitable for beginners under Windows environment. It is a free software and complies with GPL (GNU General Public License) sub source code.

πŸ‘‰πŸ‘‰Vim It is developed from Vi (text editor) and has the functions of compilation and error jump programming. Vim and Emacs (integrated development environment and text editor) is the favorite text editor for Unix system users.

πŸ‘‰πŸ‘‰C runtime library (C run-time library) is the Library file required by the program at runtime. Usually, the runtime Library is provided in the form of Lib or DLL. The most commonly used parts (the most basic and commonly used functions) in C language are separated to form header files and corresponding libraries, which form the C runtime Library. C + + is a superset of C. The Standard C++ Library added by VC for C + + mainly includes libcp LIB,LIBCPMT.LIB and msvcprt LIB.

πŸ‘‰πŸ‘‰GNU GNU is a free operating system. Its content is completely released in GPL. GNU is similar to Unix, but does not contain Unix code with copyright (Unix is not open source and closed). Linux / Linux (GNU for short) combines with Linux to produce a complete operating system.

πŸ‘‰πŸ‘‰GCC (GNU Compiler Collection) is a programming language translator developed by GNU and a set of programming language compilers developed by GNU. GCC was originally called GNU C Compiler. GCC was originally used to deal with C language, but later expanded to deal with more programming languages such as C + +, Java, etc., so it was renamed GNU compiler suite.

3. The first C + + program

πŸ‘‰πŸ‘‰ C + + ⊇ C, C + + is a superset of C, that is, C + + is compatible with C.

🐾🐾C++ It has been upgraded based on C. let's witness the first C + + program. The C + + code is as follows:

#Include < iostream > / / input / output stream header file
using namespace std;//All identifiers in the C + + standard library are defined in a namespace named std

int main(){
    //Input and output functions commonly used in C + +
    cout << "please input a string:" << endl;
    char string[100];
    cin >> string;
    cout << string << endl;
    //C common input and output functions
    printf("please input a string:\n");
    scanf("%s",string);
    printf("%s\n",string);
    //Call the pause command pause of DOS system to pause the execution of the program. Press any key to continue the execution.
    system("pause");
    return 0;
}

4. Data type

πŸ‘‰πŸ‘‰ The basic types of C + + include bool, char, int, float, double, void (no type), wchar_t (wide character), etc. some basic types can be modified with one or more type modifiers, including signed, unsigned, short, long and other modifiers.

🐾🐾Enumeration type (enumeration) is a derived data type in C + +. It is a collection of user-defined enumeration constants.

enum Enumeration name(){
	Identifier 1(=Integer constant),
	Identifier 2(=Integer constant),
	...
	identifier  n(=Integer constant)
} Enumerating variables;

🐾🐾 The default value of the first enumeration member is integer 0, and the values of subsequent enumeration members are incremented by 1 in turn. In addition, the enumerator can be assigned to integer variables, but not vice versa. The C + + code is as follows:

/* Data type enumeration type */
int main(){
    enum sex{boy,girl};
    enum weekday{Mon,Tue,Wed,Thu,Fri,Sat,Sun}weekday1,weekday2;
    int a = boy;//Assign an enumeration variable to an integer variable.
    int b = girl;
    weekday1 = Tue;//weekday1 and weekday2 are weekday types.
    weekday2 = weekday1;
    int i = weekday2;
    int j = Wed;
    cout << a << endl;
    cout << b << endl;
    cout << i << endl;
    cout << j << endl;
    system("pause");
    return 0;
}

πŸ†šπŸ†š Operation results:

0
1
1
2

πŸ“ŒπŸ“Œ Example: randomly select two days' rest time from a week and output how many different combinations there are. The C + + code is as follows:

/* Enumeration type instance */
/* Two days of rest were randomly selected from a week */
#Include < iostream > / / input / output stream header file
#Include < iomanip > / / I / O stream format control header file, just like the formatted output in C
using namespace std;//All identifiers in the C + + standard library are defined in a namespace named std
int main(){
    enum restday_set{Mon,Tue,Wed,Thu,Fri,Sat,Sun};
    restday_set restday;//Enumeration type variable
    int count=0;
    for(int i=Mon;i<=Sun;i++){//The default value of Mon is 0, and the value of Sun is 6.
        for(int j=i+1;j<=Sun;j++){
            if(i!=j){
                count++;
                cout << count;
                for(int c=1;c<=2;c++){
                    switch(c){
                        case 1:restday=(restday_set)i;break;
                        case 2:restday=(restday_set)j;break;
                    }
                    switch(restday)
                    {
                        case 0: cout << setw(5) << "Mon"; break;//setw is used to set the output field width.
                        case 1: cout << setw(5) << "Tue"; break;
                        case 2: cout << setw(5) << "Wed"; break;
                        case 3: cout << setw(5) << "Thu"; break;
                        case 4: cout << setw(5) << "Fri"; break;
                        case 5: cout << setw(5) << "Sat"; break;
                        case 6: cout << setw(5) << "Sun"; break;
                    }
                }
                cout << endl;
            }
        }   
     }
     cout << "There are " << count << " options for your rest days." << endl;
     system("pause");
     return 0;
}

πŸ†šπŸ†š Operation results:

1  Mon  Tue
2  Mon  Wed
....
20  Fri  Sun
21  Sat  Sun
There are 21 options for your rest days.

5. Storage class

πŸ‘‰πŸ‘‰ Storage classes define the scope (visibility) and life cycle of variables / functions in C + + programs. These specifiers are placed before the type they modify. Storage classes can be divided into auto (local variable), register (local variable), static (local and global), extern (global variable), mutable (object only for class) and thread_local( C++ 11 New definition, thread cycle, etc.

🐾🐾 Use the extern keyword to declare and reference global variables. Global variables are visible to all program files. They are usually used when two or more files share the same global variables or functions; Modifying a local variable with the static keyword can maintain the value of the local variable between function calls. When modifying a global variable, the scope of the variable will be limited to the file that declares it. helloworld.cpp code is as follows:

/* Storage class */
#Include < iostream > / / input / output stream header file
#include "helloworld.h"
using namespace std;//All identifiers in the C + + standard library are defined in a namespace named std
/* Global function func2, scope in all program files.*/
extern void func2(void);
/* Static global variable a, whose scope is limited to the program file in which it is declared. */
static int a = 6;
/* Common global variable count. If it is not initialized during declaration, the system will automatically initialize it to 0. */
int count;
void func()
{
/* The static local variable b, the scope is a local scope. After the first initialization, the calling function is no longer initialized. */
    static int b = 9;
    b++;
    cout << "a=" << a <<" "<< "b=" << b <<endl;
}
int main(){
    while (a--)
    { 
        func();
        count++;
    }
    func2();
    system("pause");
    return 0;   
}

🐾🐾 helloworld.h code is as follows:

#include <iostream>
using namespace std;

/* Global variable count */
extern int count;
void func2(void){
    cout << "The number of runs is " << count << endl;
}

πŸ†šπŸ†š Operation results:

a=5 b=10
a=4 b=11
a=3 b=12
a=2 b=13
a=1 b=14
a=0 b=15
The number of runs is 6

🐾🐾 Mutable storage class can only be used for data members of the class, not ordinary variables. The data members of classes with mutable properties break the const limit of class objects and allow modification of data members modified by mutable keyword in the class, even if other members of the class are still const read-only attributes.

/* mutable Storage class */
#include <iostream>
using namespace std;
class A
{
public:
//The variable modified by mutable keyword will always be in a variable state even in const function.
    void test() const;
    mutable bool flag;  
    int id;//id member variable cannot be modified
};
//The function modified by const keyword is to protect the member variables in the class.
void A::test() const{
    flag = true;
//Definition id = 1; In member function 'void A::test() const' will be reported, and the member variable cannot be modified.
    cout << flag << endl;
    cout << id << endl;
}
int main(){
    A a;
    a.test();
    system("pause");
    return 0;
}

πŸ†šπŸ†š Operation results:

1
0

🐾🐾 Using thread_ The variable declared by the local keyword can only be accessed on the thread on which it is created. Variables are created when the thread is created and destroyed when the thread is destroyed. Each thread has its own copy of the variable. The C + + code is as follows:

#include <iostream>
#include <thread>
using namespace std;

/* For global variables, thread_local variables are added separately in each thread and do not interfere with each other. */
thread_local int n = 1;
void func1(){
    n++;
/* this_thread::get_id()Method can get the thread ID of the current thread, which is used to verify that the main thread and the child thread are two different threads */   
    cout << "thread number is " << this_thread::get_id() << " n=" << n << endl;
    //printf("thread number is %d, n=%d\n",this_thread::get_id(),n);
    //cout if there is a problem with the output format, use printf() to verify.
}
void func3(){
/* As a local variable, thread_ The local variable will automatically static. */
/* thread_local Although the storage cycle of the variable is changed, the service cycle or scope of the variable is not changed */
    thread_local int m = 0;
    cout << "thread number is " << this_thread::get_id() << " m=" << m << endl;
    //printf("thread number is %d, m=%d\n",this_thread::get_id(),m);
    m++; 
}
/* Run twice (func3) */
void func2(){
    func3();
    func3();
}
int main(){
    n++;
    func1(); //Main route t, n=3
    
    thread t2(func1);//Child thread t2,n=2
    thread t3(func1);//Sub thread t3,n=2
    
	/* The main thread waits for the execution of the sub thread to complete before continuing. */
    /* After the sub thread ends, the main thread is responsible for recycling the sub thread resources. */
    t2.join();
    t3.join();

    func2();//Main route t,n=0,n=1
    thread t4(func2);//Child thread t4,n=0,n=1
    thread t5(func2);//Sub thread t5,n=0,n=1
	
    t4.join();
    t5.join();

    //system("pause");

    return 0;
}	

πŸ†šπŸ†š Operation results:

thread number is 140737348192064 n=3

[New Thread 0x7ffff7a53700 (LWP 2977)]
thread number is 140737348187904 n=2

[New Thread 0x7ffff7252700 (LWP 2978)]
[Thread 0x7ffff7a53700 (LWP 2977) exited]
thread number is 140737339795200 n=2
thread number is 140737348192064 m=0
thread number is 140737348192064 m=1
[Thread 0x7ffff7252700 (LWP 2978) exited]

[New Thread 0x7ffff7252700 (LWP 2979)]
thread number is 140737339795200 m=0
thread number is 140737339795200 m=1

[New Thread 0x7ffff7a53700 (LWP 2980)]
[Thread 0x7ffff7252700 (LWP 2979) exited]
thread number is 140737348187904 m=0
thread number is 140737348187904 m=1
[Thread 0x7ffff7a53700 (LWP 2980) exited]

[Inferior 1 (process 2976) exited normally]

Note:

  1. Starting from C++ 17, the auto keyword is no longer the C + + storage class specifier, and the register keyword is discarded;
  2. If the operation reports an error: 'a' was declared 'external' and later 'static' indicates that the static global variable cannot be used to transfer the same variable in multiple files, but can only work in the file declaring it, but it can ensure that other files can use variables with the same name;
  3. In C + +, mutable is also set to break through the restriction of const. The variable modified by mutable will always be in a variable state, even in a const function.

——>The above content is about the basic knowledge of C + + (I). I hope it can help beginners or re learners. I have a solid foundation and am not afraid of wind and rain! If the above contents are wrong or incomplete, please put forward! I will continue to write every blog post!
πŸ‘πŸ‘πŸ‘

To be continued
——Wen you
πŸ™ŠπŸ™ŠπŸ™Š

Welcome to watch and ask questions!!!
πŸ‘πŸ‘πŸ‘

Keywords: C++ Back-end

Added by sorenchr on Sun, 30 Jan 2022 21:43:42 +0200