C ++ primer Reading Notes-Chapter 5

Source: Internet
Author: User

Chapter 1 expressions

Expression_r is the lowest-level computation in a C ++ program. It is composed of one or more operators connected with one operator (operands ).
Each expression of 'distinct' produces a result. An expression can be used as an operand. Therefore, you can use multiple operators to compile a composite expression.
If you need to store the operation results when solving the expression, the compiler automatically creates a temporary object without a name (temporary object). These objects will be released after the maximum peripheral expression ends.
Whether the explain expression is legal or what the legal expression means (What operation is executed and what type the result is) depends on the type of the operand.

⒌ ⒈ Arithmetic Operator
Sort by priority from high to low:
Mona1 positive +, mona1 negative-; multiplication *, Division/, modulo %; Addition +, subtraction-
Division/
(1) The result of division of two integers is still an integer, and the fractional part of the quotient is truncated.
(2) One positive integer, one negative integer, and the result value is rounded to the 0 side or to the-∞ side, depending on the machine.
Modulo
(1) the operand can only be an integer.
(2) When both operands are negative, the result is negative or 0;
When two operands are positive and negative, the result symbol depends on the machine.

Linearregression Relational operators and logical operators
Sort by priority from high to low:
Non-logical !; Less than <, less than or equal to <=, greater than>, greater than or equal to >=; equal =, not equal! =; Logic and &; logic or |
The operator and the logical operator accept arithmetic or pointer-type operands and returnBoolType Value
Logical operators regard their operands as conditional expressions
Combine logic and & and logic or | the operator supports short-circuit evaluation (short-circuit evaluation)
The operator should not be concatenated to use Relational operators.
If the expression I <j <K is not expected

⒌ Bitwise Operator
Sort by priority from high to low:
Bitwise inversion ~; Shift left <, shift right>; bit and &; bit are different or ^; bit or |
The bitwise operator uses integer operands and treats them as a set of binary digits.
Since how to handle the negative integer symbol bit depends on the machine, you should useUnsignedInteger operand

⒌ ⒋ Operator
The left operand of the assign value operator must be non-ConstLeft
The result of the value assignment expression is its left operand (left value)
The distinct value assignment operator combines right-to-left. Therefore, when all operands have the same common type, values can be assigned multiple times in an expression, for example:
I = J = k = 0;
⒊ Compound value assignment operator
For any Binary Arithmetic Operators or binary operators op
A op = B;
Equivalent
A = A op B;
The significant difference between the two is that the former only calculates the left operand once, and the latter calculates the left operand twice.

⒌ Auto-increment and auto-subtraction Operators
The increment auto-increment ++ and auto-increment-operators provide a convenient and short implementation method for adding 1 or minus 1 to an object. They can be used in either the front or the back.
The prefix operation returns the object (left value) after the plus (minus) 1, and the post operation returns the original value of the operand (right value)
For performance considerations, the suffix operator should be used only when necessary.
The post operator needs to save the original value for return, and the PRE operator only needs to add (subtract) 1 and then directly return the object.

⒌ ⒍ Arrow Operator
The arrow operator is used to obtain a member pointing to a class object.
The following two expressions are equivalent:
P-> Foo;
(* P). Foo;

Operator
The distinct condition operator is the only ternary operator in C ++.If-ElseStatement embedding expression
Format: Cond? Expr1: expr2
Calculate the cond value first. If it is true, calculate and return expr1, which is
If this parameter is set to false, the system returns the expr2 value.
Depth Nesting is avoided to ensure readability

ZookeeperSizeofOperator
BytesSizeofReturns the size (in bytes, type) of an object or type.
Size_t)
Format:SizeofExpr
OrSizeof(Type_name)
BytesSizeofThe result of the expression is the compile time.
Use the expressionSizeofThe value of this expression is not calculated.
StructSizeofThe length of the entire array in the memory is obtained.

Comma-separated Operator
A comma expression is a group of expressions separated by commas. It is calculated from left to right and returns the value of the rightmost expression. (If the expression is left, the return value is left)

ZookeeperNewAnd
DeleteExpression
BytesNewAnd
DeleteExpressions are used to dynamically create and release a single object or an array.
BytesNewExpression
(1)NewThe expression dynamically creates a single object or an array, and returns a pointer to the object or the first element of the array.
① When the dimension of a dynamic array is 0, a valid Non-zero pointer is returned, but cannot be referenced.
② DynamicConstObjects or arrays, which cannot be modified but can be released
③ If the required space cannot be obtained, the system will throw a bad_alloc exception.
(2) allocation and object (OR array element) initialization
① Default built-in types are not initialized, and class types call the default constructor (required)
Single Object:New[Const] Type name
An array:New[Const] Type name [dimension]
② Add null parentheses () to execute value Initialization)
That is, the built-in type object is set to 0, and the class type object calls the default constructor (required)
Single Object:New[Const] Type name ()
An array:New[Const] Type name [dimension] ()
NOTE: For the latter, in the compiler I use, the VC will set the element to 0 after initialization, but the mingw will not
③ Execute direct Initialization
Single Object:New[Const] Type name (initialize)
The initialization method similar to dynamic array elements is not supported.
BytesDeleteExpression
(1)NewDynamically allocated objects or arrays need to be explicitly used
DeleteExpression release (otherwise it may cause memory leakage)
(2)DeletePTR and
Delete[] PTR releases a single object and a dynamic array respectively
① If the pointer does not pointNewThe assigned object
DeleteInvalid
Exception: Zero pointerDeleteYes
② Read and write released objects or multiple times for the same memory spaceDeleteMay cause errors.
ThereforeDeleteThen the pointer value should be reset immediately (usually reset to 0)
③ Releasing dynamic arrays if square brackets [] are lost, errors that cannot be found by the compiler may occur.

Evaluate the ⒌ ⒑ compound expression
A compound expression (compound expression_r) contains two or more operators)
The combination of operands and operators determines the values that conform to the expression. The former depends on the operator's priority and combination:
The combination of the operand priority and the operator with a higher priority is determined by the combination.
Parentheses () are above priority
If you are not sure about the combination method, use parentheses () to forcibly determine the combination of operands.
The merge method does not mean that the calculation order of the operands is not determined.
If the value of the operand is modified, do not use it elsewhere in the same statement unless the calculation order of the operand is not a problem.
Bytes
Operator priority and associativity table

⒌ ⒓ Type conversion
Implicit type conversion
If there is a convertible relationship between two types, it is called two types.
(1) When
When the compiler expects to get some type of data but get another type, it will try to automatically convert the type
Details include:
① Multiple operands of different types in the expression are converted to the same type
② The expression used as the condition is convertedBoolType
③ When a variable is initialized or assigned a value using an expression, the former is converted to the latter type
④ Implicit type conversion may occur when passing real parameters and return values to the Function
(2) built-in type conversion rules
① Conversions between arithmetic types
When I float type is converted to integer type, the fractional part is discarded (in case of assignment or initialization)
Ii. In binary (arithmetic, relational, etc.) operator expressions, small types are converted to larger types in order to retain precision
A type upgrade
· CompareIntSmall integer
IntOr (whenIntWhen it is insufficient to accommodate all possible values of the original type)Unsigned
Int
· SetFloatUpgraded
Double
BSignedAnd
UnsignedConversion
·SignedSmall Type and
UnsignedLarge or the same type, the former is converted to the latter
·SignedLarge types and
UnsignedSmall type, how to operate depends on the machine:
If the former can represent all possible values of the latter, the latter is converted to the former; otherwise, all values are converted to the formerUnsignedForm
In the preceding two cases, negative values may be convertedUnsignedCause overflow and unexpected results
② Convert to pointer
The array name in expression I is automatically converted to a pointer to the first element of the array.
Except in the following cases:
Array A is used as the operand to get the address operator &
Array BSizeofOperator operations
C. When initializing the array with array references
II pointer to any type of object can be convertedVoid* Type
Type III integer constant 0 can be converted to any pointer type
BoolType conversion
Convert the I arithmetic value and pointer valueBoolType
0 → false non-0 →
True
BoolConvert value to arithmetic type
True → 1
False → 0
④ Convert enumeration members to integer type
Enumeration type objects or enumeration members can be automatically converted to Integers (the specific type depends on the maximum value of the machine and enumeration members, but at least INT)
⑤ ConvertConstObject
NonConstObjects in the initialization
ConstAutomatically convertedConst
NonConstThe object address or point to a non-
ConstObject pointers can also be convertedConstObject Pointer
Implicit type conversion
(1) If possible, avoid forced type conversion.
Be careful when using it.
(2) name forced type conversion
Dynamic_cast
Used for runtime type recognition (rtti)
Const_cast
Can add or remove pointers, data member pointers, or referencesConstFeatures
Static_cast
I can explicitly complete any type conversion implicitly executed by the compiler
Compiler warning caused by potential loss of precision will be disabled
· Can be used to avoid unnecessary implicit conversions, such
Known D isDouble, I is
Int, Write I * = D; as I * =Static_cast<Int> (D); you can save the trouble of converting I
DoubleThis unnecessary step
Reinterpret_cast
Provides a lower-level re-interpretation for the bit mode of the operand. The result depends on the compiler and machine.
Improper use may cause runtime errors
(3) forced conversion of old types
In legal useStatic_castOr
Const_castTo provide the same function as forced name conversion.
If neither of the two conversions is valid, executeReinterpret_cast
It is not recommended because it is difficult to identify the potential risks of each explicit conversion.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.