C c++ internal mind skill – Basic chapter

Time:2022-6-20

Hello, everyone. Today, I will tell you about some basic syntax of c++. I have compiled some simple basic knowledge, which is also very helpful for our programming.

C++ cin

CIN in c++ is an istream object, which reads data from standard input and defines it in iostream header file.
CIN has a buffer, the input buffer. The first input process is like this. When a keyboard input is completed, the input data will be stored in the input buffer, and the CIN function directly takes the data from the input buffer. Because the CIN function directly fetches data from the buffer, sometimes when there is residual data in the buffer, the CIN function will directly obtain these residual data without requesting keyboard input, which is why sometimes the input statements become invalid.

1.cin>> function usage: This is the most frequently used input stream for learning c++ at first.

Usage 1 Accept the input of a string and end with “space”, “tab” and “carriage return”.

2.cin. The usage of get() has three forms, cin get(),cin. get(char ch),cin. get(array,length)。

Usage 1 cin. get()
Used to read a character. The end condition is carriage return. However, carriage return and spaces in the buffer will not be discarded. Cin Get() and cin Get (char CH) functions are basically the same, char = cin Get() and cin Get (char CH) is the same.

#include
using namespace std;
int main()
{
  char c,ch;
  c = cin.get();
  cin.get(ch);
  cout<<;
  cout<<;
  return 0;
}
Enter: a enter (enter a character and then enter)
Output: a
(there is a line here)
Input: ABCD enter
Output: a b

Usage 2 cin. Get (char CH) is the same as 1
Usage 3 cin. Get (array, length) accepts the input of a string, accepts the input length-1 characters, and the last one is stored as’ \0 ‘.

#include
using namespace std;
int main()
{
      char ch[10];
   cin.get(ch,5);
   cout<<;
   return 0;
}
Input: ABCDEFG enter
Output: ABCD

3.cin. The usage of getline() is to accept the input of a string, including spaces, and stop when a carriage return is encountered.

Usage 1 cin. getline()

#include
using namespace std;
int main()
{
  char ch[10];
  cin.getline(ch,5);
  cout<<;
  return 0;
}

Input: aaaaaaaa
Output: AAAA

4. Getline() function, which accepts the input of a string containing spaces. When a carriage return is encountered, it should contain

#incldue。
Usage 1 getline(cin,sting s)  
#include
#include
using namespace std;
int main()
{
  string s;
  getline(cin,s);
  cout<<;
  return 0; 
}

Input: ABCDEFG enter
Output: ABCDEFG

5. The get() function accepts the input of a string containing spaces. When a carriage return stops, it should contain \incldue。

Usage 1: receive the input of a string.

#include
#include
using namespace std;
int main()
{
    char ch[10];
  gets(ch);
  cout<<;
  return 0; 
}

Input: ABCDEFG enter
Output: ABCDEFG

6. Getchar() accepts a character input, including spaces. When a carriage return stops, it should include \incldue。

Usage 1: accept one character input

#include
#include
using namespace std;
int main()
{
   char ch;
   ch = getchar();
   cout<<;
   return 0; 
}
Input: ABC enter
Output: a

Cout output principle

1. Use overloading: functions of different types are overloaded according to the type of output content, so you can output a variety of types, including user-defined types.

For example, in cout, there are many cout functions with the same name, but they have different types of parameters, such as int float char. When the “output content” is of type char, call the cout function with the parameter char

2. Open buffer: when defining each stream object, the system will open a buffer in memory to temporarily store data (there are multiple buffers in the system). When the endl is received, the cout line will wrap and the buffer will be flushed. Cout output process: first put the output characters into the buffer, and then output them to the screen.

——When the buffer is full or the end character is received, the buffer data will be emptied and output on the display device.

C ++ printf

Printf output principle

1. Type is specified by%d,%f, etc;
2. Output without buffer.

Format section

Cout:std:: cout< example: std:: cout < < cout output < < std:: endl;

Printf:printf (“other +% conversion + other”, parameter);
Example: printf (“cout output”);

Printf printing speed

Comparison of printing efficiency between CIN, cout, scanf and printf in c++

If you are an IO player or an ACM player, try not to use CIN or cout. Try printing 9999999. The speed difference between them is about 10 times

C c++ function overloading

C C++ Name-mangling

Name mangling means that the name used in the symbol table of the object file and in the connection process is usually different from the name in the source program that compiles the object file. The compiler adjusts the name in the object source file. Name mangling is not a very new technology. For example, it also exists in C language. We often see the underlined “_” when assembling C language The function name at the beginning is actually the name mangling of the function name by the C compiler. But in c++, name mangling is much more complicated. Because c++ supports overload and override, the c++ compiler must have a completed name mangling to adjust the function name or variable name.
Name demangling in compiler
When we know the method of c++ compiler name mangling, we can resolve and restore the original function prototype through the reverse process, which is convenient for debugging.

C++ function overloading

When listening to function overloading for the first time, I feel that it is rather uncertain. It should be very difficult. In fact, it is very simple. It only takes one sentence to understand what function overloading is: the so-called function overloading is that it has the same function name but different parameter lists to execute different function functions. The key to function overloading lies in the parameter list of the function – which also becomes the feature of the function. It is allowed to define functions with the same name in c++, provided that their characteristics must be different, that is, the parameter list must be different. This difference can be parameter type, parameter number, parameter order, etc. Let’s give some simple examples to introduce function overloading.

void show(const char*str,int n);//$1
void show(double d,int n);//$2
void show(long l,int n);//$3
void show(int k,int n);//$4
void show(const char*str);//$5

When using function overloading, you should pay attention to the following points:

1. type reference and type itself are the same type of feature. As follows:

double fix(double x);
double dix(double &x);

On the surface, the characteristics of the two functions are different. They should be overloaded functions. If you think they are overloaded functions, you are very wrong. We can see from the naked eye that they are different, but the compiler doesn’t think so. He thinks they are the same. Suppose there is the following Code:
cout<The compiler thinks that the parameter x matches both the double x prototype and the double &x prototype. Which one should I call. In order to avoid this confusion, the compiler will refer to the type reference and the type itself as the same type when checking the function signature.

2. when matching functions, const and non const variables are not distinguished. See the following example

//Function definition
void fun1(const char*str);
void func(char*str);
void fun2(const char *str);
void funb(char *str);
//Function call
const char a[8]="cake";
char b[7]="brand";
fun1(a);
fun1(b);
func(b);
funb(a);// Error calling, because a is const char* and funb() is char*,
//Make non const variables ->const variables legal, otherwise, illegal
fun2(b);

3. the function can be overloaded because of the feature, not the function type. For example, the following two declarations are mutually exclusive.

long gank(int x,int y);
int gank(int x,int y);

Keep in mind that it is not allowed to overload gank () in this way in c++. The return types can be different, but the characteristics must be different.

C implementation function overloading

Why add an extern “C” declaration when calling a function compiled by the C compiler in a c++ program?
(1) In c++, you can compile a function in the style of C language by adding extern “C” before the function declaration.
(2) C++ language supports function overloading. C does not support function overloading.
(3) The names of functions compiled in C and c++ are different. Adding extern “C” indicates that C has been compiled.

C++ wants to call the compiled C functions. Because the compiled names are different, they cannot be called directly. Therefore, c++ and external “C” life are added to solve this problem.

//ModuleA header file
#ifndef __ MODULE_ A_ H // for module a, this macro is used to prevent repeated references to header files
#define __MODULE_A_H
int fun(int, int);
#endif
 
//ModuleA implementation file modulea C // the implementation of module a remains unchanged
#include"moduleA"
int fun(int a, int b)
{
return a+b;
}
 
//Moduleb header file
#idndef __ MODULE_ B_ H // obviously, this part is also used to prevent repeated references
#define __MODULE_B_H
#ifdef __ Cplusplus // this part tells the compiler that if the__ Cplusplus (that is, if it is a cpp file, extern "C" {// because the cpp file defines the macro by default), it is compiled in C
#include"moduleA.h"
#endif
... // other codes
 
#ifdef __cplusplus
}
#endif
#endif
 
//Moduleb implementation file moduleb The implementation of the CPP //b module has not changed, but the design of the header file has changed
#include"moduleB.h"
int main()
{
  cout<<fun(2,3)<;
}

C++ const keyword summary

Const is the abbreviation of constant. Its original meaning is unchangeable. In c++ it is used to modify built-in type variables, custom objects, member functions, return values, and function parameters.
C++ const allows you to specify a semantic constraint, which is enforced by the compiler, allowing the programmer to tell the compiler that a certain value remains unchanged. If you do have a value that remains unchanged in your programming, you should explicitly use const, so that you can get help from the compiler.
1、 Const modifies a variable of common type
const int a = 7;
int b = a; // correct
a = 8; // Error, cannot be changed
A is defined as a constant, and a can be assigned to B, but a cannot be assigned again. It is illegal to assign a value to a constant because a is considered a constant by the compiler and its value cannot be modified.
Next, see the following operations:
example

#include
using namespace std;
int main(void)
{
    const int  a = 7;
    int  *p = (int*)&a;
    *p = 8;
    cout<;
    system("pause");
    return 0;
}

For const variable a, we take the address of the variable and assign it to the pointer pointing to int, and then use *p = 8; Reassign the value in the address of variable a, and then output the value of view a. From the debug window below, you can see that the value of a is changed to 8, but the output is still 7. From the results, we can see that the compiler then thinks that the value of a is 7 defined at the beginning, so the operation on const a will produce the above situation. Therefore, do not try to assign values to const variables easily, which will produce unexpected behavior. If we don’t want the compiler to be aware of the above operations on const, we can add the volatile keyword before const.
The volatile keyword is opposite to const. It is changeable and easy to change. Therefore, it will not be optimized by the compiler, and the compiler will not change the operation of a variable.
example

#include
using namespace std;
int main(void)
{
    volatile const int  a = 7;
    int  *p = (int*)&a;
    *p = 8;
    cout<;
    system("pause");
    return 0;
}
The output is 8 as we expected.

2、 Const modifies a pointer variable.

Const decorated pointer variables have the following three cases.
A: Const modifies the content pointed to by the pointer, then the content is non variable.
B: Const modifies a pointer, then the pointer is non variable.
C: Const modifies the pointer and the content pointed to by the pointer, so both the pointer and the content pointed to by the pointer are immutable.

For a:
const int *p = 8;
The content 8 pointed to by the pointer cannot be changed. It is called left fixed value for short, because const is on the left of the * sign.
For b:
int a = 8;
int* const p = &a;
*p = 9; //  correct
int  b = 7;
p = &b; //  error
The memory address pointed to by const pointer P cannot be changed, but its contents can be changed. Abbreviation: right orientation. Because const is to the right of the * sign.
For c: the combination of a and B
int a = 8;
const int * const  p = &a;
At this time, the content and memory address pointed to by const P are fixed and cannot be changed.
For the three cases a, B and C, according to the different positions of const in the * sign, I summarize three sentences for easy memory: "left fixed value, right orientation, const modifier invariant".

3、 Const parameter passing and function return value.

The const modifier function parameters can be divided into three cases.
A: The const modification of value transfer is not required in this case, because the function will automatically generate temporary variables to copy the argument values.
example

#include
using namespace std;
void Cpf(const int a)
{
    cout<;
    // ++a;   Is wrong, a cannot be changed
}
int main(void)
{
    Cpf(8);
    system("pause");
    return 0;
}

B: When the const parameter is a pointer, the pointer can be prevented from being accidentally tampered with.
example

#include
using namespace std;
void Cpf(int *const a)
{
    cout<<*a<<" ";
    *a = 9;
}
int main(void)
{
    int a = 8;
    Cpf(&a);
    cout<; //  A is 9
    system("pause");
    return 0;
}

C: The parameter transfer of custom types requires the temporary object to copy parameters. For the construction of temporary objects, the constructor needs to be called, which is a waste of time. Therefore, we adopt the method of const plus reference transfer.
And for general built-in types such as int and double, we do not use the reference transfer method.
example

#include
using namespace std;
class Test
{
public:
Test(){}
Test(int _m):_cm(_m){}
int get_cm()const
{
       return _cm;
}
private:
    int _cm;
};
void Cmf(const Test& _tt)
{
    cout<.get_cm();
}
int main(void)
{
    Test t(8);
    Cmf(t);
    system("pause");
    return 0;
}
Result output 8.

For the return value of const decorating function.
The return value of const decoration can be divided into three cases.
A: Const modifies the return value of a built-in type. Modifying the return value is the same as not modifying the return value.
example

#include
using namespace std;
const int Cmf()
{
    return 1;
}
int Cpf()
{
    return 0;
}
int main(void)
{
    int _m = Cmf();
    int _n = Cpf();
 
    cout<<<" "<;
    system("pause");
    return 0;
}

B: Const modifies a custom type as the return value. At this time, the returned value cannot be used as an lvalue. It cannot be assigned or modified.
C: Const modifies the returned pointer or reference. Whether a pointer to const is returned depends on what we want the user to do.

4、 Const decorated class member function

Const modifies class member functions to prevent member functions from modifying the value of the called object. If we do not want to modify the value of a calling object, all member functions should be declared as const member functions.
Note: the const keyword cannot be used with the static keyword at the same time, because the static keyword modifies the static member function. The static member function does not contain the this pointer, that is, it cannot be instantiated. The const member function must be specific to an instance.
Get below_ cm()const; Function uses const member function:
example

#include
using namespace std;
class Test
{
public:
Test(){}
Test(int _m):_cm(_m){}
 int get_cm()const
 {
      return _cm;
  }
private:
    int _cm;
};
void Cmf(const Test& _tt)
{
    cout<.get_cm();
}
int main(void)
{
    Test t(8);
    Cmf(t);
    system("pause");
    return 0;
}

If get_ Cm() removes the const modifier, then the const passed by CMF_ TT even if the value of the object is not changed, the compiler also thinks that the function will change the value of the object, so we try to treat all functions that do not need to change the content of the object as const member functions as required.
What if a member function wants to modify a member in an object? At this time, we can use the mutable keyword to modify this member. The meaning of mutable is also changeable. The member modified by the mutable keyword can be in constant change, as shown in the following example.
example

#include
using namespace std;
class Test
{
public:
    Test(int _m,int _t):_cm(_m),_ct(_t){}
    void Kf()const
    {
        ++_ cm; //  error
        ++_ ct; //  correct
    }
private:
    int _cm;
    mutable int _ct;
};
int main(void)
{
    Test t(8,7);
    return 0;
}

Here we pass kf() const++_ ct; Modification_ The value of CT, but through++_ Cm modification_ CM will report an error. Because++_ Cm is not decorated with mutable.

Green mountains do not change, green water flows, see you later, thank you for your support!