C++ Fundamentals Originally published in Chinese on 2015-07-05; this English edition preserves the original scope and technical context.
const Related #define,typedef,const # is a macro that does not perform type checking but only performs simple substitution; it is processed before compilation, and the result of macro processing is the code of the compilation stage. typedef is used to declare custom data types, simplifying the code. const is used to define constants with a data type, and the compiler performs type checking on them. const and Pointer const char *p: p is a pointer to const char char const *p; p is a pointer to char const. char *const p: p is a const pointerchar int main() { const char *p1 = new char('a'); char const *p2 = new char('b'); char *const p3 = new char('c'); *p1 = 'd'; // error: read-only variable is notassignable *p2 = 'e'; // error: read-only variable is notassignable p3 = new char('f'); // error: cannot assign tovariable 'p3' with const-qualified type 'char *const' p3 = nullptr; // error: cannot assign to variable'p3' with const-qualified type 'char *const' } const and Class Members When const is used to modify a member function of a class, the function cannot modify the class’s member variables or call non-const member functions of the class. When const is used to modify a function parameter, the value of the parameter cannot be modified within the function. When const is used to modify a function return value, the variable receiving the return value must also be declared as const. class Base { public: int i = 1; const int *Func(const int &j) const { const int *k = new int(1); i = 1; // error: cannot assign to non-static data member within const member function 'Func' j = 1; // error: cannot assign to variable 'j' with const-qualified type 'const int &' return k; } void Test() { i = 2; } }; int main() { Base obj; int j = 1; int *k = obj.Func(j); // error: cannot initialize a variable of type 'int *' with an rvalue of type 'const int *' return 0; } Static Related 1. Procedural Approach **Modifiers static global variables, the scope of the static global variables only applies to the current source file. The construction of global variables occurs before the main function. **Modifiers static global functions, the scope of the static global functions only applies to the current source file. **Modifiers local variables, the scope of the static local variables only applies to the current function; the variable is initialized for the first time it is encountered, allocated in the global data area, and deallocated when the function ends. Object-Oriented For member variables of a class, static member variables affect all instances of the class, and their memory is allocated in the global data area; these variables can be directly accessed through the class name.
...