C++ data type (two)


A C++ program can be defined as a collection of objects that interact by calling each other's methods.

  • Object-has behavior and status.
  • Class-a collection of objects with the same characteristics, which are abstract, not real.
  • Methods-A class can contain multiple methods, you can write Logitech in the methods, manipulate data, and perform actions. It is usually called a function in c++.
  • Even variables-Each object has unique even variables, and the state of the object is created by the values ​​of these even variables.

C++ program structure

#include <iostream> //头文件
using namespace std; //命名空间,std
// main() 是程序开始执行的地方
 
int main()
{
    
    
   cout << "Hello World"; // 输出 Hello World
   return 0; //终止main函数
}

Compile and execute C++ programs

How to save the source code in a file?

  • Open a text editor (such as txt) and add the above code
  • Save the file as hello.cpp
  • Open the command prompt window cmd and enter the directory where the file is saved
  • Input g++ hello.cpp, hit enter, compile the code, it will generate a.out
  • Enter a.outto run the program
  • You can see that Hello World
    beginners need to understand this method, which helps to understand the past and present of the program. This method is basically not used in actual development.

Statement block

{
    
    
   cout << "Hello World"; // 输出 Hello World
   return 0;
}

It is a group of logically connected statements enclosed in braces.

Identifier

It is the name used to identify variables, functions, classes, modules or any other user-defined items, starting with a letter or underscore, followed by a letter underscore or number
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal

Keyword

Insert picture description here

Trigram

A three-character group is a sequence of three characters used to represent another character, also known as a three-character sequence. A three-character sequence always starts with two question marks.

Three-character sequences are not very common, but the C++ standard allows certain characters to be specified as three-character sequences. In the past, this was an indispensable method to represent characters that were not on the keyboard.

Three-character sequences can appear anywhere, including strings, character sequences, comments, and preprocessing instructions.

The most commonly used three-character sequences are listed below:
Insert picture description here
If you want two consecutive question marks in the source program and do not want to be replaced by the preprocessor, this situation occurs in character constants, string literals, or program comments , The alternative method is to use automatic concatenation of strings: "...?" "?.." or escape sequence: "...??..".

Starting from Microsoft Visual C++ 2010, the compiler no longer automatically replaces trigrams by default. If you need to use three-character replacement (for example, to be compatible with ancient software codes), you need to set the compiler command line option /Zc:trigraphs

g++ still supports tri-characters by default, but will give a compilation warning.

Comment

  • // Generally used for single-line comments
  • /*. . */ Generally used for multi-line comments

type of data

Seven data types:

  1. Integer int
  2. Floating point type float
  3. Double floating point
  4. Character char
  5. Bool
  6. Typeless void
  7. Wide character type wchar_t
typedef short int wchar_t;

So the actual space of wchar_t is the same as short int.
java中是八大数据类型:byte short int long float double char boolean
The following table shows the memory that various variable types need to store in memory, as well as the maximum and minimum values ​​that can be stored in this type of variable.
Note: Different systems will be different, one byte is 8 bits.
Note: long int is 8 bytes, int is 4 bytes. Early C compilers defined long int to occupy 4 bytes and int to occupy 2 bytes. The new version of the C/C++ standard is compatible with earlier versions of this standard. One setting.
Insert picture description here

Variables and constants

The beginner students will definitely be confused and may be confused by the inappropriate examples given by the teacher. Here, let me talk about the definition I gave them, and I won’t give an example for now.

  • Variable: the amount that the appearance does not change, the value will change
  • Constant: Generally, it is a specific value, and the value cannot be modified.

Such as: int a; a is a variable. a can be equal to 0, 1, 2...
Variables have global variables and local variables. The difference is that at different locations, global variables will be initialized automatically, while local variables must be initialized manually.
C++ also allows the definition of various other types of variables, such as enumerations, pointers, arrays, references, data structures, classes, and so on. . .

define和const

Define is the preprocessor, that is, the amount that cannot be modified after the global definition.

#include <iostream>
using namespace std;
 
#define LENGTH 10   
#define WIDTH  5
#define NEWLINE '\n'
 
int main()
{
    
    
   int area;    
   area = LENGTH * WIDTH;
   cout << area;
   cout << NEWLINE;
   return 0;
}

The const keyword
declares constants of the specified type 程序中只读不能修改.

const int  LENGTH = 10;
const int  WIDTH  = 5;
const char NEWLINE = '\n';
int area;  

the difference

  1. Type and security check are different: Macro definition (#define) is character substitution, there is no difference in data type.
  2. The compiler handles differently: macro definition is a compile-time concept, and const is a runtime concept.
  3. The storage method is different: the macro definition is direct replacement, no memory is allocated, and stored in the code segment, and const needs to be allocated memory and stored in the data segment of the program.
  4. The definition domain is different, the macro definition is global, and const is within the function.
  5. Macro definition can be cancelled by #undef
  6. const can be passed as function parameters, but not macro definitions.

The difference between const char*, char const*, char*const

Modifier type

The signed
unsigned
long
short
piece of code fully understands:

#include <iostream>
using namespace std;
/* 
 * 这个程序演示了有符号整数和无符号整数之间的差别
*/
int main()
{
    
    
   short int i;           // 有符号短整数
   short unsigned int j;  // 无符号短整数
   j = 50000;
   
   i = j;
   cout << i << " " << j;
   return 0;
}
//运行结果:-15536 50000

Type qualifier

  • const: Objects of const type cannot be modified during program execution.
  • volatile: The volatile modifier tells the compiler that it does not need to optimize the variables declared by volatile, so that the program can read variables directly from memory. For general variable compilers, variables will be optimized, and variable values ​​in memory will be placed in registers to speed up reading and writing efficiency.
  • restrict: A pointer modified by restrict is the only way to access the object it points to. Only C99 adds the new type qualifier restrict.

Storage class

The storage class defines the scope (visibility) and life cycle of variables/functions in C++ programs. These specifiers are placed before the types they modify. The storage classes available in C++ programs are listed below:

auto
register
static
extern
mutable
thread_local (C++11)

Starting from C++ 17, the auto keyword is no longer a C++ storage class specifier, and the register keyword is deprecated.

auto

Since C++11, the auto keyword has been used in two situations: when declaring a variable, it automatically infers the type of the variable based on the initialization expression, and when declaring a function 返回值的占位符.

The auto keyword in the C++98 standard is used for the declaration of automatic variables, but it has been removed in C++11 due to its minimal use and redundancy.
The type of the declared variable is automatically inferred according to the initialization expression, such as:

auto f=3.14;      //double
auto s("hello");  //const char*
auto z = new auto(9); // int*
auto x1 = 5, x2 = 5.0, x3='r';//错误,必须是初始化为同一类型

register

The original meaning of the register is to define a local variable stored in the register instead of the memory. It means that the maximum size of the variable is equal to the size of the register (usually a word), and you cannot use & because it is not in memory.
Only used for variables that need quick access, such as counters. Also, after register modification, it is not necessarily stored in the register, depending on hardware and implementation limitations.

static

The static storage class instructs the compiler to maintain the existence of local variables during the life of the program, without the need to create and destroy each time it enters and leaves the scope. Therefore, using static to modify local variables can maintain the value of local variables between function calls.
The static modifier can also be applied to global variables. When static modifies a global variable, the scope of the variable is limited to the file in which it is declared.
In C++, when static is used on a class data member, it will cause only one copy of the member to be shared by all objects of the class.
1). Static member variables exist before the objects of
the class 2). All objects of this class share a static member
3). If the static member is public, then it can be called directly by the class name
4). The static member data is in declared outside the class initialization time
that white is 类变量.

#include <iostream>
 
// 函数声明 
void func(void);
 
static int count = 10; /* 全局变量 */
 
int main()
{
    
    
    while(count--)
    {
    
    
       func();
    }
    return 0;
}
// 函数定义
void func( void )
{
    
    
    static int i = 5; // 局部静态变量
    i++;
    std::cout << "变量 i 为 " << i ;
    std::cout << " , 变量 count 为 " << count << std::endl;
}

When the above code is compiled and executed, it will produce the following results:

变量 i 为 6 , 变量 count 为 9
变量 i 为 7 , 变量 count 为 8
变量 i 为 8 , 变量 count 为 7
变量 i 为 9 , 变量 count 为 6
变量 i 为 10 , 变量 count 为 5
变量 i 为 11 , 变量 count 为 4
变量 i 为 12 , 变量 count 为 3
变量 i 为 13 , 变量 count 为 2
变量 i 为 14 , 变量 count 为 1
变量 i 为 15 , 变量 count 为 0

extern storage class

The extern storage class is used to provide a reference to a global variable, which is visible to all program files. When you use'extern', for variables that cannot be initialized, the variable name will point to a previously defined storage location.

When you have multiple files and define a global variable or function that can be used in other files, you can use extern in other files to get a reference to the defined variable or function. It can be understood that extern is used to declare a global variable or function in another file.

The extern modifier is usually used when two or more files share the same global variable or function, as shown below:

The first file: main.cpp

#include <iostream>
int count ;
extern void write_extern();
int main()
{
    
    
   count = 5;
   write_extern();
}

The second file: support.cpp

#include <iostream>
extern int count;
void write_extern(void)
{
    
    
   std::cout << "Count is " << count << std::endl;
}

Here, the extern keyword in the second file is used to declare the count that has been defined in the first file main.cpp. Now, compile these two files as follows:

$ g++ main.cpp support.cpp -o write

This will produce the write executable program, try to execute write, it will produce the following results:

$ ./write
Count is 5
``

mutable storage class

The mutable specifier only applies to objects of the class, which will be explained at the end of this tutorial. It allows members of an object to substitute for constants. In other words, mutable members can be modified through const member functions.

thread_local storage class

A variable declared with the thread_local specifier can only be accessed on the thread on which it was created. Variables are created when the thread is created, and destroyed when the thread is destroyed. Each thread has its own copy of variables.

The thread_local specifier can be combined with static or extern.

You can use thread_local only for data declarations and definitions, and thread_local cannot be used for function declarations or definitions.

The following demonstrates the variables that can be declared as thread_local:

thread_local int x;  // 命名空间下的全局变量
class X
{
    
    
    static thread_local std::string s; // 类的static成员变量
};
static thread_local std::string X::s;  // X::s 是需要定义的
 
void foo()
{
    
    
    thread_local std::vector<int> v;  // 本地变量
}

Guess you like

Origin blog.csdn.net/qq_43600467/article/details/112446410