C + + Primer learning notes and thinking _10 type conversion easy mistakes big Summary

Source: Internet
Author: User

(i) implicit conversion

Let's look at a set of examples:

int ival=0;ival=3.451+3;

To do the addition operation first, the operands are int and double, C + + does not add two numbers directly, but instead provides a set of conversion rules to convert two operands to the same data type before performing arithmetic operations. This is done automatically here, so they are being implicitly converted.
Because C + + defines a built-in conversion between arithmetic types to prevent the loss of precision as much as possible, here 3 is converted to a double type with a sum of 6.451. However, when the next assignment is made, the right operand is truncated and the accuracy is lost, and the compiler gives a warning.
2. Common implicit conversions
① mixed-type expressions, operands are converted to the same type (as in the previous example)
int ival=0;double dval;ival>=dval;
② an expression used as a condition is converted to a bool type
int Val;if (val) while (Val)
③ A variable is initialized with an expression, or an expression is assigned to a variable, the expression is converted to a variable type.
int Ival=3.21;int *ip;ip=0; The int converted to a null pointer of type int *
3. Conversions defined by the standard library type
String S;while (Cin>>s)
This implicitly uses the type conversion defined by the IO standard library, which returns CIN, where the value of the IStream type is converted to type bool, which means that it verifies the state of the stream, and if the read succeeds, returns true if it fails, for example to read to the end of the file, then false after conversion to bool , the circulation condition is not tenable.
(ii) Explicit conversions
①static_cast
Usage: static_cast < Type-id > (expression)
Description: This operator converts expression to the Type-id type, but does not have run-time type checking to guarantee the security of the conversion.
1. Any type of conversion implicitly performed by the compiler can be done by the static_cast explicit conversion.
2 using casts is especially useful when you need to convert a large arithmetic type to a smaller type, note that this time the compiler will no longer prompt for warnings because this tells the compiler that we know and do not care about potential precision loss.
3. Using static_cast to perform type conversions is also useful for situations where the compiler does not provide automatic conversions.
Double D =5.6;void* p=&d;double *dp=static_cast<double*> (*p);
②const_cast
As the name implies, the Const property in the expression is converted.
The constant pointer is converted to a very pointer, and still points to the original object, and the constant reference is converted to a very literal reference and still points to the original object;
③reiterpret_cast
Reinterpret_cast is meant to map to a completely different type of meaning, and this keyword is used when we need to map the type back to the original type. The type we map to is just for the sake of the trick and other purposes, which is the most dangerous of all mappings. (This is the phrase in C + + programming idea).
Other wordswe just think of int* as the char* type.
It can convert a pointer to an integer, or it can convert an integer to a pointer (a pointer is converted to an integer, the integer is converted to the original type of pointer, and the previous pointer value can be obtained).
Incorrect use of reinterpret_cast can easily lead to unsafe programs, only converting the converted type values back to their original type, so that the Reinterpret_cast method is used correctly. However, it is prudent to use the reinterpret_cast.
④dynamic_cast
The dynamic_cast operator is used to convert a pointer to a base class type or a reference to a pointer or reference that is safe to a derived type. He can decide the real type in the execution period. If the downcast is safe (say,if a base class pointer or reference does point to a derived class objectThis operator returns the appropriately transformed pointer. If downcast is unsafe, this operator will pass go home pointers (that is, the base class pointer or reference does not point to a derived class object), and for reference it is an exception that throws the Bad_cast type.
The dynamic_cast is primarily used for upstream and downstream conversions between class hierarchies, and can also be used for cross-conversion between classes.
The effect of dynamic_cast and static_cast is the same when the upstream conversion is performed between class hierarchies;
In the downstream conversion, dynamic_cast has the function of type checking, which is more secure than static_cast.
Also note: A should have virtual function, otherwise it will compile error; static_cast does not have this limitation.
This isbecause run-time type checking requires run-time type information, this information is stored in the class's virtual function table(With regard to the concept of virtual function tables, in detail <inside C + + object model>), only classes that define virtual functions have virtual function tables, and classes that do not define virtual functions have no virtual function tables.
#include <iostream> #include <string> #include <cstring> #include <algorithm>using namespace Std;class a{int a;virtual void P () {}//must};class b:p ublic  a{int b;}; int main () {B nameb;  A Namea; A *p1=&namea; A * p = &nameB; b* cur = dynamic_cast<b*> (p); OK P point to bb* cur1 = dynamic_cast<b*> (p1);  ERROR,NULL,P1 does not point to b//cout << cur << endl;try{a &k = Namea; B &temp = dynamic_cast<b&> (k);} catch (bad_cast) {cout << "bad_cast" << Endl;}}
(iii) Legacy casts
The type conversions provided by standard C + + enhance the visibility and security of conversions, and legacy casts rely on the data types involved, with the same behavior as Const_cast,static_cast and reinterpret_cast. In places where static_cast or const_cast are legitimately used, legacy casts provide the same functionality as their corresponding named casts. If neither of these conversions are legal, the legacy cast performs the Reinterpret_cast function, as follows:
int ival;double dval;ival+=int (dval); Static_cast:converts double to Intconst char* pc_str;string_copy ((char*) pc_str);//const_cast casts away Constint *ip; Char*pc= (char*) p; Reinterpret_cast:treats int* as char*

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + Primer learning notes and thinking _10 type conversion easy mistakes big Summary

Related Article

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.