当前位置:网站首页>[c++ primer notes] Chapter 4 expression
[c++ primer notes] Chapter 4 expression
2022-06-27 07:51:00 【Little silly bird_ coding】

Author's brief introduction : Bo Lord stay read machine device people study investigate raw , Objective front study One . Yes meter count machine after End sense xing boring , xi huan c + + , g o , p y t h o n , Objective front Ripe Learned c + + , g o language said , Count According to the library , network Collateral Ed cheng , 了 Explain branch cloth type etc. phase Turn off Inside Rong \textcolor{orange}{ The blogger is studying robotics graduate , Currently, Yanyi . Interested in the back end of the computer , like c++,go,python, Currently familiar with c++,go Language , database , Network programming , Understand the distribution and other related contents } Bo Lord stay read machine device people study investigate raw , Objective front study One . Yes meter count machine after End sense xing boring , xi huan c++,go,python, Objective front Ripe Learned c++,go language said , Count According to the library , network Collateral Ed cheng , 了 Explain branch cloth type etc. phase Turn off Inside Rong
individual people Lord page : \textcolor{gray}{ Personal home page :} individual people Lord page : Little silly bird _coding
the a : \textcolor{gray}{ Support :} the a : Such as fruit sleep have to Bo Lord Of writing Chapter also No wrong or person you use have to To Of word , can With Exemption fee Of Turn off notes One Next Bo Lord , Such as fruit 3、 ... and even closed hidden the a Just more good La \textcolor{green}{ If you think the blogger's article is good or you can use it , You can follow the blogger for free , It would be better if the three collections support } Such as fruit sleep have to Bo Lord Of writing Chapter also No wrong or person you use have to To Of word , can With Exemption fee Of Turn off notes One Next Bo Lord , Such as fruit 3、 ... and even closed hidden the a Just more good La Just yes to Give I most Big Of the a ! \textcolor{green}{ Is to give me the greatest support !} Just yes to Give I most Big Of the a !
Abstract of this article
This column is mainly about c++ primer The summary of this Bible , And relevant notes for each chapter . I am reviewing this book now . At the same time, I hope I can help you , After learning this book . This article mainly explains the 4 Chapter expression List of articles
- ️ The first 4 Chapter expression
- ️4.1 Basics
- ️4.2 Arithmetic operator
- ️4.3 Logical and relational operators
- ️4.4 Assignment operator
- ️4.5 Increment and decrement operators
- ️4.6 Member visit
- ️4.7 Conditional operator
- ️4.8 An operator
- ️4.9 sizeof Operator
- ️4.10 The comma operator
- ️4.11 Type conversion
- ️4.12 Operator priority ( Omit p147)
️ The first 4 Chapter expression
️4.1 Basics
️4.1.1 Basic concepts
Operand conversion
Small integer type ( Such as bool、char、short etc. ) It is usually promoted to a larger integer type , Mainly int type- Generally, when performing binary operators , Even if the two number types are different , As long as they can change to the same type with each other .
- When an operator is applied to an operand of a class type , The user can define what it means . This practice is called
Overload operator
Left and right
- c The left value in the can be on the left side of the assignment statement , And the right value is not
- c ++ expression
Or lvalue , Or right value - The left value : When an object is used as an lvalue , It's using
The identity of the object ( Location in memory ) - Right value : When an object is used as an R-value , It's using
The value of the object ( Content )
Where an R-value is required, it can be replaced by an l-value , But you can't take right as left ( That's location ) Use .
- Use keywords decltype when , If the expression evaluates to an lvalue ,decltype Act on the expression ( Is not a variable ) Get a reference type .
for example
int *p;
decltype(*p) The result is int&;
- Operator has requirements on whether the action object is an lvalue or an lvalue , For example, the left operand of the assignment operator must be an lvalue .
️4.1.2 Priority and combination law
- The law of left Union : If the operators have the same precedence , Combine operands from left to right .
- Most binary operators satisfy the left associative law , The assignment operator satisfies the right binding law .
️4.1.3 Order of evaluation
- Priority specifies the combination of operands , But it doesn't specify the order in which operands are evaluated .
int i = f1() * f2();
function f1 And the function f2 Must be called before multiplication , But it is f1() stay f2() The previous call is still , Then call , Not sure
- For operators that do not specify an execution order , If the expression points to and modifies the same object , Then there will be a mistake
cout << i << ""<< ++i << end;// error ! Undefined behavior , I don't know what to ask first i Or ask for ++i
Processing compound statements
- In the case of uncertain priority and associative law , Force parentheses
If you change the value of an operation object , Do not use this operand in the same expression .
️4.2 Arithmetic operator
Arithmetic operator ( The law of left Union ), There are three kinds of
- +、- : A dollar plus sign and a dollar minus sign
- *、/、% : Multiplication 、 division 、 Seeking remainder
- +、- : Add 、 Subtraction
- All operators above , All satisfy the left Union Law , Means the same priority , Combine from left to right .
The result of integer division is to 0 integer- The operation object of the remainder operation must be an integer , The result of the operation is always the same as the sign of the dividend
-21 % -8 = -5
21 % -5 = 1
️4.3 Logical and relational operators
- Logical operators :!、&&、||
- Relational operator :<, <=, >, >=, !=, ==
- The evaluation results of both logical and relational operators are
Boolean value. Short circuit evaluation: Logic and operator and logic or operator are to find the value of the left operand first and then the value of the right operand , The value of the right operand is evaluated when and only when the left operand cannot determine the result of the expression .First left and then right- Declaring as a reference type avoids copying elements , as follows , Such as string Especially large can save a lot of time .
vector<string> text;
for(const auto &s: text){
cout << s;
}
Be careful : If you want to test the true value of an arithmetic object or pointer object , The most direct way is to use it as if The condition of the statement , Do not compare with Boolean values .
if(a);// correct as long as a yes Positive numbers , It is true
if(a == true);// error : Will true First convert to int Compare again , The comparison results are not equal ( Only a = 1 When it's true )
️4.4 Assignment operator
- Of assignment operation
Its left operand when the result is returned, And it's aThe left value. Type is the type of the object on the left . - If the left and right operand types of assignment operation are different , The right operand is converted to the type of the left operand .
- The assignment operator satisfies the right binding law
int i, j;
i = j = 1;// correct ,j To be an assignment 1, And then i To be an assignment j Value .
Equivalent to
i = (j = 1);
- Assignment priority
A relatively low, In a conditional statement , The assignment section should normallyAdd brackets - Compound assignment operator , The compound operator only evaluates once , The ordinary operator evaluates twice .
- Bit operations can also use assignment operators .
+=; -=; *=; /=; %=; <<=; >>=; &=; ^=; |=;
for example a = a + 1; Two operations are required
and a += 1; Only one operation is required
️4.5 Increment and decrement operators
There are two forms of increment and decrement operators :
- Pre version :++i , Get the incremented value .( First +1, In the operation )
- Post version :i++, Get the value before incrementing .( Calculate first , stay +1)
The previous version returns the object itself as an lvalue , The Post version returns a copy of the original value of the object . Not necessary , Do not use the Post version There are two reasons :
- The pre version directly returns the changed operand , The Post version needs to save the original value so that it can be returned , It's a waste .
- Post versions have little effect on integers and pointers , But it's expensive for iterators .
Mix dereference and increment operators in a single statement
pbeg++ Equivalent to *(pbeg++)
- pbeg++, hold pbeg The value of the add 1, Then return pbeg As a result of its evaluation .
- The increment operator takes precedence over dereference , So don't use parentheses
- It is suggested to write this way , It's simple
auto pbeg = v.begin();
while(pbeg != v.end())
cout << *pbeg++ << endl;
️4.6 Member visit
Dot operatorandArrow operatorsCan access members ..The priority of the operator is greater than*, So remember to add parenthesesptr->memEquivalent to(*ptr).mem
️4.7 Conditional operator
- Conditional operator (
?:), Allow us to put the simpleif-elseLogic is embedded in a single expression , The format of the conditional operator iscond ? expr1: expr2; - You can use nested conditional operators
Conditional operators have low priority , Generally, parentheses should be added
int final = (grade > 90) ? "high pass":(grade < 60)? "fail":"pass"
️4.8 An operator
Bitwise operators act on Integer types The object of , And treat the operator object as Binary digit Set .
| Operator | function |
|---|---|
| ~ | Position inversion |
| << | Move left |
| >> | Move right |
| & | Bit and |
| ^ | Bit exclusive or |
| ! | Bit or |
- If the operand is “ Small integer ”, The value is automatically promoted to a larger integer type .
- Operands can be signed , It can also be without a symbol .
The result of an unsigned operation is fixed , The result of a signed operation depends on the machine . The shift left operation may change the value of the sign bit , So in c++ It is recommended that only bit operations be used to handle unsigned types
Shift Operators
- Use the shift operator , The number of digits moved must be strictly less than the number of digits of the result . Otherwise, undefined behavior will occur .
>>The shift right operator handlesAn unsigned numberwhen , It is equivalent to inserting... On the left 0, The value of the right out of the boundary is discarded<<The shift left operator handlesAn unsigned numberwhen , It is equivalent to inserting... On the right 0, The value of the left out boundary is discarded
For signed bits :
<<Shift left operator , It is equivalent to inserting a value of 0 Binary bit of>>Shift right operator : If the operand is of unsigned type , It is equivalent to inserting a value of 0 Binary bit of . If there is a symbol type , Insert a copy of the symbol on the left or the value is 0 Binary bit of , Depending on the environment
The shift operator satisfies the left union law
cout << a << b << endl;
((cout << a) <<b ) << endl;
️4.9 sizeof Operator
sizeofReturns the number of bytes occupied by an expression or a type name , The return value issize_ttype- sizeof Satisfy the right union law
- sizeof and
Does not actually calculate the value of its operand.
sizeof There are two forms :
- sizeof (type), Give the type name
- sizeof expr, Give the expression
Sales_data data *p;
sizeof p; // The space occupied by the pointer
sizeof *p //P The size of the type indicated , for example int * p ; here p The size of int The size of the type
- Execute... On an array sizeof Operator gets the size of the space occupied by the entire array . Does not convert an array to a pointer to handle .
- But execute on the pointer sizeof Operator gets the size of the pointer type , That is to say 8.
- Yes string or vector Object to perform sizeof The operation only returns the size of the fixed part of the type , It doesn't count how much space the elements in the object take up .
- It can be used sizeof Gets the number of elements in the array :
int ia[10];
// sizeof(ia) Returns the size of the space occupied by the entire array
// sizeof(ia)/sizeof(*ia) Returns the size of the array
constexpr size_t sz = sizeof(ia)/sizeof(*ia);
int arr[sz];
️4.10 The comma operator
Evaluate from left to right .
Left evaluation result discarded , The result of the comma operator is the value of the expression on the right .
stay for Two different conditions in a loop can be separated by commas
for(int i=0; i!=n; i++,j++)
Be careful not to use commas to separate different conditions in the judgment conditions , That will only return the value of the last expression separated by commas .
️4.11 Type conversion
stay c++ in , If the two objects participating in the operation are of different types . will Through type conversion , Unify the types of the two objects , It's calculating
Implicit type conversion
- Than int Integer values of small types are first promoted to larger integer types
- Under conditions , Convert non Boolean values to Boolean values
- In the initialization , The initial value is converted to the type of variable .
- assignment , The right operands are converted to the left type
- There are many types of operands for arithmetic operations or relational operations , Convert to one .
- Function calls also have transformations .
️4.11.1 Arithmetic conversion
The operand in the operator , Convert to The widest type . for example : When there are both floating-point numbers and integers in the expression . The integer value will be replaced by the corresponding floating-point type
double c = 3 + 'a';// First the 'a' Ascend to int, And then put int convert to double
Integer promotion
Integer promotion is responsible for converting small integers to larger integer types .
for example :(bool, short, char etc. ), As long as all their possible values can exist int in , They will be promoted to int type
Unsigned operands
- If one is unsigned and the other is signed . If the unsigned type is not less than the signed type ( For example, all of them are 4 byte ), Then signed is converted to unsigned
- If unsigned type is less than signed , The conversion result depends on the machine . Try not to use .
️4.11.2 Other implicit type conversions
Convert array to pointer
- In most cases, the array is automatically converted to a pointer to the first element of the array .(decltype Key parameters 、 Fetch address (&)、sizeof、typeid Will not happen )
Pointer conversion
Integers 0ornullptrCan be converted to any pointer type .- A pointer to a non constant can be converted to void*. Pointers to all objects can be converted to const void*.
Convert to constant
Allow to point to Pointer of non constant type Convert to point to the corresponding constant type The pointer .
int i;
const int &j = i; // The non constant is converted into const int quote
const int *p = &i; // The non constant address is translated to const The address of
int &r = j, *q = p; // error : Don't allow const Convert to non constant
Class type definition conversion
string s = "value";// take c The style string literal is converted to string type
while(cin>>s); // take cin Convert to bool value
️4.11.3 Display conversion
Display conversion is a forced conversion
The specific format of the cast :
castname<type>(expression);
castname There are four kinds. :
- static_cast
- dynamic_cast
- const_cast
- reinterpret_cast
static_cast
Any type conversion , As long as it doesn't include the bottom layer const, Both can be used. static_cast
double slope = static_cast<double>(j)/i; // take j convert to double To perform floating-point division
- When converting a larger type to a smaller type ,static_cast It is useful to . At this point it tells the reader and the compiler : We know and don't care about the loss of accuracy . Usually the compiler will give a warning , No warning after explicit conversion .
const_cast
- const_cast Only the bottom layer of the object can be changed const. Can be removed or added const nature .
- Only const_cast Can change the constant property of an expression , Nothing else .
- cosnt_cast It is often used in the context of function overloading .
string& s;
const_cast <const string&> (s);// take s Convert to constant reference
const_cast <string&> (s);// take s Convert back to non constant references
reinterpret_cast
Don't use it .
Old style cast
int(a);// Casts in function form
(int)a;// c Forced type conversion of language style
- Old style cast essentially uses const_cast、static_cast or reinterpret_cast A kind of .
- The old style is less clear than the new style , If something goes wrong , Tracking difficulties .
️4.12 Operator priority ( Omit p147)
边栏推荐
- Speech signal feature extraction process: input speech signal - framing, pre emphasis, windowing, fft- > STFT spectrum (including amplitude and phase) - square the complex number - > amplitude spectru
- JS output all prime numbers between 1-100 and calculate the total number
- js例题打印1-100之间所有7的倍数的个数及总和
- js输出1-100之间所有的质数并求总个数
- Mobile security tools -jad
- Implementation principle of similarity method in Oracle
- Origin of forward slash and backslash
- 爬一个网页的所有导师信息
- 准备好迁移上云了?请收下这份迁移步骤清单
- 2022 love analysis · panoramic report of it operation and maintenance manufacturers
猜你喜欢

MySQL

Basic knowledge | JS Foundation

js用switch语句根据1-7输出对应英文星期几

How to view program running time (timer) in JS

基础知识 | js基础

File and multipartfile overview

Multi table associated query -- 07 -- hash join
![【批处理DOS-CMD命令-汇总和小结】-批处理命令中的参数%0、%1、%2、%[0-9]、%0-9和批处理命令参数位置切换命令shift,dos命令中操作符%用法](/img/05/19299c47d54d4ede95322b5a923093.png)
【批处理DOS-CMD命令-汇总和小结】-批处理命令中的参数%0、%1、%2、%[0-9]、%0-9和批处理命令参数位置切换命令shift,dos命令中操作符%用法

【批处理DOS-CMD命令-汇总和小结】-环境变量、路径变量、搜索文件位置相关指令——set、path、where,cmd命令的路径参数中有空格怎么办

Helix QAC更新至2022.1版本,将持续提供高标准合规覆盖率
随机推荐
VNC Viewer方式的远程连接树莓派
js中如何查看程序运行时间(计时器)
JS print 99 multiplication table
1-4 decimal representation and conversion
Mysql-8 download, installation and configuration tutorial under Windows
参考 | 升级 Win11 移动热点开不了或者开了连不上
期货反向跟单—交易员的培训问题
若xn>0,且x(n+1)/xn>1-1/n(n=1,2,...),证明级数∑xn发散
Speech signal feature extraction process: input speech signal - framing, pre emphasis, windowing, fft- > STFT spectrum (including amplitude and phase) - square the complex number - > amplitude spectru
Sword finger offer 07 Rebuild binary tree
05 观察者(Observer)模式
淘宝虚拟产品开店教程之作图篇
(resolved) NPM suddenly reports an error cannot find module 'd:\program files\nodejs\node_ modules\npm\bin\npm-cli. js‘
语音信号处理-概念(一):时谱图(横轴:时间;纵轴:幅值)、频谱图(横轴:频率;纵轴:幅值)--傅里叶变换-->时频谱图【横轴:时间;纵轴:频率;颜色深浅:幅值】
Websocket database listening
2、项目使用的QT组件
js打印99乘法表
[compilation principles] review outline of compilation principles of Shandong University
What is a magnetic separator?
游戏六边形地图的实现