C++ Basic Tutorial (1)

C++ Elementary Tutorial

1. Introduction to C++

C++ (c plus plus) is a high-level computer programming language, which is produced by the extension and upgrading of C language . It was first developed in 1979 by Benjani Stroustrupp at AT&T Bell Studios.

C++ can not only carry out procedural programming of C language , but also carry out object-based programming characterized by abstract data types , and can also carry out object-oriented programming characterized by inheritance and polymorphism. While C++ is good at object-oriented programming, it can also perform process-based programming. C++ can create almost any type of program: games, device drivers , HPC , cloud , desktop , embedded and mobile applications , etc. Even libraries and compilers for other programming languages ​​are written in C++.

C++ has the practical characteristics of computer operation, and is also committed to improving the programming quality of large-scale programs and the problem description ability of programming languages.

2. Use of C++

The C++ language is widely used in many industries and fields, including:

  • Game development: C++ is one of the most used programming languages ​​in the field of game development because of its efficient performance and ability to directly control hardware. Many major game engines, such as Unreal Engine and Unity, are written in C++.
  • Embedded system development: C++ can play an important role in embedded systems such as smartphones, cars, robots, and home appliances. Because embedded systems often have strict resource constraints and real-time requirements, the efficient performance and memory control features of C++ are very useful.
  • Financial field: C++ is widely used in the financial field, such as high-frequency trading, algorithmic trading, and risk management. Since these applications require efficient performance and direct control of the hardware, the C++ language is a suitable choice.
  • Graphics and image processing: C++ can be used to develop graphics and image processing applications, such as computer vision, computer graphics and artificial intelligence. Since these applications require efficient computing power and control over hardware, C++ is a good choice.
  • Scientific computing and numerical analysis: C++ can be used to develop scientific computing and numerical analysis applications, such as numerical simulation and high-performance computing. Since these applications require efficient computing power and direct control of the hardware, the C++ language is a good choice.

3. Output Hello world

All codes in this tutorial are done in Dev C++ .

1. Create a new project

Upper left corner: File---->>New---->>Project, select Empty Project , C++ project , set the project name to day01, and click OK.
insert image description here

2. Write code

Write the following code in the created file:

#include<iostream>//引入头文件
using namespace std;//命名空间

int main()//主函数
{
    
    
	cout<<"Hello world";//cout用于输出内容到控制台
	return 0;//返回值
}

After the code is written, click Save and set the file name. Compile and run the code (F11), and get the following results:

Hello world

In C language family programs, header files are widely used. In general, every C++/ C program usually consists of a header file and a definition file . As a carrier file containing function functions and data interface declarations, the header file is mainly used to save the declaration of the program, while the definition file is used to save the implementation of the program.

The header file contains some commonly used functions and methods, so when using some specific functions or methods, you need to import the corresponding header file.

The main function is the entry point of the C++ program, and all functions and methods need to be executed through the main function. The main function is also unique. A program can only have one main function. If multiple main functions are defined at the same time, an error will be reported.

A namespace is a declarative area that provides a scope for the identifiers (names of types, functions, variables, etc.) within it. Namespaces are used to organize code into logical groups and also to avoid name conflicts, especially when the base code includes multiple libraries. All identifiers within namespace scope are visible to each other without any restrictions. Identifiers outside a namespace can std::vector<std::string> vec;access members by using each identifier's fully qualified name (for example), a using declaration for a single identifier, or a using directive ( ) for all identifiers in the namespace using namespace std;. Code in header files should always use fully qualified namespace names.

4. C++ keywords

asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template

5. C++ identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier begins with the letters AZ or az or the underscore _ followed by zero or more letters, underscores, and digits (0-9).

Note: Identifiers cannot start with numbers, cannot contain other special symbols except underscore (_) , and reserved words (keywords) cannot be used as constant names, variable names or other identifier names .

Punctuation characters such as @, &, and % are not allowed within C++ identifiers. C++ is a case-sensitive programming language. Therefore, in C++, Manp and manp are two different identifiers.

6. C++ Notes

Program comments are explanatory statements that can be included in C++ code to improve the readability of the source code. All programming languages ​​allow some form of comments. Comments are not executed when the program is running, and all characters in comments will be ignored by the C++ compiler.

C++ supports single-line comments and multi-line comments. There are generally two types of C++ comments:

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

Comments start with // and continue until the end of the line. For example:

#include <iostream>
using namespace std;
 
int main() {
    
    
  	// 这是单行注释
    /*
    这是多行注释
    */
  cout << "Hello World!";
  return 0;
}

Seven, C++ data types

C++ provides programmers with a rich variety of built-in data types and user-defined data types. The following table lists the seven basic C++ data types:

type keywords
Boolean bool
character type char
integer int
floating point float
double float double

The specific differences between each data type will be explained in the following content.

8. Variables in C++

A variable is really nothing more than the name of a memory area that a program can manipulate. Each variable in C++ has a specified type, which determines the size and layout of variable storage. Values ​​within this range can be stored in memory, and operators can be applied to variables.

1. Variable naming rules

Variable names can consist of letters, numbers, and the underscore character. It must start with a letter or underscore. Uppercase and lowercase letters are different because C++ is case sensitive.

2. Definition of variables

Format: data type variable name;, for example:

int a;

You can also define multiple variables at the same time, just use "," to separate the variable names, for example:

double a,b,c;
char c1,c2;

3. Initialization

Initialization, that is, assigning values ​​to variables.

Assignment uses "=", note that this symbol is not equal to, but an assignment character.

For example:

//定义变量
int a,b,c;
//初始化变量
a = 1;
b = 2;
c = 3;

At the same time, you can also assign values ​​directly when defining variables. For example:

//定义变量并直接赋值
int a=1;
int b=2;
//一行中定义多个变量并赋值
double c=1.1,d=2.5,e=3.3;

Note: Variables must be initialized before they can participate in operations .

9. Operators in C++

1. Arithmetic operators

operator describe
+ adds two operands
- Subtracts the second operand from the first operand
* multiply two operands
/ divides two operands
% Modulo (remainder) operator, remainder after division
++ Increment operator, increments an integer value by 1
Decrement operator, decrements an integer value by 1

For example:

int a=2,b=3,c=4;
cout<<a+b;// 2+3=5
cout<<a-b;// 2-3=-1
cout<<a*b;// 2*3=6
cout<<a/b;// a/b=0
cout<<a%b;// a%b=2

Note: In C++, when two integers are divided, the result is also an integer ( the result is rounded, and attention is not rounded ).

The existing code is as follows:

#include<iostream>
using namespace std;

int main()
{
    
    
	int a=2,b=3;
	cout<<a++<<" "<<--b;
	return 0;
}

The output is:

2 2

Why is this?

In C++, the operation logic of the self-increment and self-decrement operators is related to the position of the operator, that is to say, the results obtained by a++ and ++a are different. What is the operational logic?

When the operator is before the variable, the variable needs to be incremented or decremented first, and then other operations are performed; if the operator is after the variable, other operations need to be performed first, and then the variable is incremented or decremented. This is why the final output of a++ is 2 .

For example, there are the following examples:

#include<iostream>
using namespace std;

int main()
{
    
    
	int a=2,b=3,c=3,d=2;
	cout<<a++<<" "<<--b<<" "<<++c<<" "<<d--;
	return 0;
}

The result is:

2 2 4 2

Analysis: the a++ operator is behind, it operates first, and then increments itself, so the output result is 2; Self-increment, then operation, so the output result is 4; the d- operator is after, first operation, and then self-decrement, so the output result is 2.

When the self-increment and self-decrement operators participate in complex expressions, the above principles are also followed.

2. Relational operators

operator describe
== Checks if the values ​​of the two operands are equal, if they are equal then the condition becomes true.
!= Checks if the values ​​of the two operands are equal, if not the condition becomes true.
> Checks if the value of the left operand is greater than the value of the right operand, if yes then the condition becomes true.
< Checks if the value of the left operand is less than the value of the right operand, if yes then the condition becomes true.
>= Checks if the value of the left operand is greater than or equal to the value of the right operand, if so then the condition becomes true.
<= Checks if the value of the left operand is less than or equal to the value of the right operand, if yes then the condition becomes true.

Relational operators are used to compare the magnitude of variables or expressions, and the result of the expression is a Boolean value, that is, true or false.

For example:

#include<iostream>
using namespace std;

int main()
{
    
    
	int a=2,b=3;
	bool f1 = a>b;
	bool f2 = a<b;
	bool f3 = a==b;
	bool f4 = a!=b;
	bool f5 = a<=b;
	bool f6 = a>=b;
	cout<<f1<<" "<<f2<<" "<<f3<<" "<<f4<<" "<<f5<<" "<<f6;
	return 0;
}

The result is:

0 1 0 1 1 0 

0 is false and 1 is true.

3. Logical operators

operator describe
&& Called the logical AND operator. The condition is true if both operands are true.
|| 称为逻辑或运算符。如果两个操作数中有任意一个 true,则条件为 true。
! 称为逻辑非运算符。用来逆转操作数的逻辑状态,如果条件为 true 则逻辑非运算符将使其为 false。

有如下代码:

#include<iostream>
using namespace std;

int main()
{
    
    
	int a=0,b=1;
	bool f1 = a&&b;
	bool f2 = a||b;
	bool f3 = !a;
	cout<<f1<<" "<<f2<<" "<<f3;
	return 0;
}

结果为:

0 1 1

4、赋值运算符

运算符 描述 实例
= 简单的赋值运算符,把右边操作数的值赋给左边操作数 C = A + B 将把 A + B 的值赋给 C
+= 加且赋值运算符,把右边操作数加上左边操作数的结果赋值给左边操作数 C += A 相当于 C = C + A
-= 减且赋值运算符,把左边操作数减去右边操作数的结果赋值给左边操作数 C -= A 相当于 C = C - A
*= 乘且赋值运算符,把右边操作数乘以左边操作数的结果赋值给左边操作数 C *= A 相当于 C = C * A
/= 除且赋值运算符,把左边操作数除以右边操作数的结果赋值给左边操作数 C /= A 相当于 C = C / A
%= 求模且赋值运算符,求两个操作数的模赋值给左边操作数 C %= A 相当于 C = C % A

例如,有如下代码:

#include<iostream>
using namespace std;

int main()
{
    
    
	int a=2,b=3,c=4,d=5,e=6,f=7;
	a+=b; // a=a+b
	b-=c; // b=b-c
	c*=d; // c=c*d
	d/=e; // d=d/e
	e%=f; // e=e%f
	cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<" "<<f;
	return 0;
}

结果为:

5 -1 20 0 6 7

5、C++ 中的运算符优先级

运算符的优先级确定表达式中项的组合,这会影响到一个表达式如何计算。某些运算符比其他运算符有更高的优先级,例如,乘除运算符具有比加减运算符更高的优先级。

例如 x = 7 + 3 * 2,在这里,x 被赋值为 13,而不是 20,因为运算符 * 具有比 + 更高的优先级,所以首先计算乘法 3*2,然后再加上 7。

下表将按运算符优先级从高到低列出各个运算符,具有较高优先级的运算符出现在表格的上面,具有较低优先级的运算符出现在表格的下面。在表达式中,较高优先级的运算符会优先被计算。

类别 运算符 结合性
后缀 () [] -> . ++ - - 从左到右
一元 + - ! ~ ++ - - (type)* & sizeof 从右到左
乘除 * / % 从左到右
加减 + - 从左到右
移位 << >> 从左到右
关系 < <= > >= 从左到右
相等 == != 从左到右
位与 AND & 从左到右
位异或 XOR ^ 从左到右
位或 OR | 从左到右
逻辑与 AND && from left to right
logical OR || from left to right
condition ?: from right to left
assignment = += -= *= /= %=>>= <<= &= ^= |= from right to left
comma , from left to right

In a complex expression, multiple different operators may be involved at the same time. At this time, it is necessary to consider the priority of the operator, and calculate the final result according to the priority. For example:

#include<iostream>
using namespace std;

int main()
{
    
    
	int a=2,b=3,c=4,d=5,e=6,f=7;
	int g=a*b+c%f+(++d>=e&&e<f)-f++;
	cout<<g;
	return 0;
}

The result is:

4

Guess you like

Origin blog.csdn.net/qq_43884946/article/details/129642329
Recommended