preface
In C we do all kinds of casts, and in C we see them all the time
memset(OTA_FLAG_ADDRESS,(uint8_t*)&OTA_Flag,sizeof(OTA_Flag));
Copy the code
C++ type conversion and C are very different, so C++ in the type conversion is how to use. C++ in addition to implicit conversion and display conversion, display conversion is known to us, there are four display conversion functions:static_cast
,dynamic_cast
,const_cast
,reinterpret_cast
, mainly used in mandatory transformation between classes of inheritance relation.
I will give you the following said.
Akik Conscience still lives
Welcome to add wechat official account: Yulinjun
Implicit conversion
**
C++ language will not directly add two different types of values, twenty first according to the type conversion rules to try to unify the type of the operand and then evaluate. For example, int value = 3.14 +3; The program will compile, but the compiler may warn of a loss of precision. Such conversions are automatic and do not require programmer intervention; therefore, they are called implicit conversions
** When implicit conversion occurs:
** The compiler automatically converts operand types in the following cases:
- In most expressions, the need to promote an integer value smaller than int to a larger integer type is implicitly cast
- In conditions, non-Boolean values are converted to Boolean types
- During initialization, the initial value is converted to the type of the variable. In an assignment statement, the right-hand operand is converted to the type of the left-hand operand
- Type conversions also occur on function calls (argument type conversions)
According to conversion
C-style casts are easy to understand. Any Type of Cast can be used in the following way
Type b = (Type)a;
Copy the code
Of course,C++ also supports C-style casts, but c-style casts can bring some pitfalls and make some problems difficult to detect. So C++ provides a set of cast functions that can be used in different situations.
**C++ provides four types of cast coercion functions: **static_cast. Most of the transformations that C does, you can just use this function.
Const_cast is literally a const property. Dynamic_cast is a dynamic type cast. Such as polymorphic type conversions between subclasses and superclasses. A reinterpret_cast simply reinterprets a type, but does not perform a binary conversion.
Static_cast:
You can use static_cast for any well-defined type conversion that does not contain an underlying const, as an example.
double slop = static_cast<double>(j) / i; Double int*pn =&n; Void *p = &n; void*p = &n; void*p = &n; Double *d = static_cast<double*>(&p) // convert void* to the original pointer typeCopy the code
The static_cast cast is checked only at compile time, but there is no runtime type checking to ensure that the cast is safe. Also, static_cast cannot remove the const, volitale, or __unaligned attribute of expression.
Const_cast:
Const_cast <> Can be converted from const to plain. Const_cast cannot be converted from one class to another. Instead, it simply converts an expression it operates on to a constant. It can convert non-const data to const or remove const attributes. If an object is not itself a constant, it is legal to use forced casting to obtain write permissions. However, if the object is a constant, writing to const_cast has undefined consequences.
Only const_cast can change the constant property of an expression. Changing the constant property of an expression using any other form of named coercion will raise a compiler error. Similarly, we cannot change the type of an expression with const_cast:
const char *cp; char *q = static_cast<char *>(cp); // Error: static_cast cannot convert const static_cast<string>(cp); // Correct: string literals converted to string const_cast<string>(cp); // error: const_cast only changes the constant attribute const_cast<char*>(cp); // const int p = 0; int &rb = const_cast<int&>(p); // correct rb =10;Copy the code
Dynamic_cast:
Dynamic_cast (); dynamic_cast (); dynamic_cast ();
2. Cannot be used to cast built-in basic data types.
Dynamic_cast returns a pointer or reference to the class on success, or NULL on failure.
If dynamic_cast is used, the base class must have virtual functions; otherwise, the compiler will fail. You can go from a parent class to a base class, but it may be null
5. Dynamic_cast and static_cast have the same effect during class conversion, when ascending between class hierarchies. Dynamic_cast is more secure than Static_cast because it has type checking for downlink conversions. An upcast is a downcast to a subclass object, that is, a parent class pointer is converted to a subclass pointer. The success of the downward conversion also depends on the type to be converted. That is, the actual type of the object to be converted must be the same as that of the converted object; otherwise, the conversion will fail.
class BaseClass { public: int Num; virtualvoid foo(){}; // Base classes must have virtual functions. Dynamic_cast}; DerivedClass: public BaseClass { public: char*m_szName[100]; void bar(){}; }; int main(int argc,char** argv) { BaseClass* pb =new DerivedClass(); DerivedClass *pd1 = static_cast<DerivedClass *>(pb); // Subclass -> parent class, static type conversion, correct but not recommended DerivedClass *pd2 = dynamic_cast<DerivedClass *>(pb); // Subclass -> parent class, dynamic type conversion, correct BaseClass* pb2 =new BaseClass(); DerivedClass *pd21 = static_cast<DerivedClass *>(pb2); // Parent class -> subclass, static type conversion, danger! DerivedClass *pd22 = dynamic_cast<DerivedClass *>(pb2); // Superclass -> subclass, dynamic type conversion, safe. The result is NULLCopy the code
Reinterpret_cast:
Reinterpret_cast reinterpret_cast reinterpret_cast reinterpret_cast reinterpret_cast reinterpret_cast reinterpret_cast reinterpret_cast reinterpret_cast But it merely reinterprets the given object’s bit model, without binary conversion! It is used to convert between arbitrary Pointers, between references, between Pointers and sufficiently large ints, and between integers and Pointers. The most common use is to convert between function pointer types. Take a look at a simple code
int doSomething(){return 0; }; typedef void(*FuncPtr)(); FuncPtr is a pointer to a function that has no parameters and returns a value of type void FuncPtr funcPtrArray[10]; Let's suppose that you want (for some puzzling reason) to store a pointer to the funcPtrArray array: funcPtrArray[0] = &dosomething; // Error compiling! FuncPtrArray funcPtrArray[0] = reinterpret_cast<FuncPtr>(&doSomething); // Convert between different function pointer typesCopy the code
Explicit keyword (explicit type conversion operator)
C++ provides the keyword explicit to prevent implicit conversions through the conversion constructor that should not be allowed. Constructors declared as explicit cannot be used in implicit conversions.
The explicit keyword can only be used on constructor declarations inside a class and not on function definitions outside the class. Now the Things class looks like this:
Class Things {public: Things(const STD ::string&name =""); explicit operator int() const{return val; } // The compiler does not automatically execute this type of};Copy the code
Here’s a better example for comparison:
// Class implicit conversion via constructor :#include <iostream> using namespace STD; class A {}; class B { public: // conversion from A (constructor): B (const A& x) {} // conversion from A (assignment): B& operator= (const A& x) {return *this; } // conversion to A (type-cast operator) operator A() {return A(); }}; int main () { A foo; B bar = foo; // Call the constructor to implement an implicit type conversion bar = foo; // calls assignment foo = bar; // calls type-cast operator, equivalent to foo = A(bar); return 0; }Copy the code
Let’s look at another example using explicit:
#include <iostream> using namespace std; class A {}; class B { public: explicit B (const A& x) {} B& operator= (const A& x) {return *this; } operator A() {return A(); }}; Void fn (B x) {} // When we want x to be only of type B, we need to disallow implicit conversions int main () {A foo; B bar (foo); // Must be explicitly cast, no longer allowed B bar = foo; bar = foo; foo = bar; // fn (foo); // Implicit type conversions are not allowed; return 0; }Copy the code
This is my share of c++ conversion type method, which refers to the text of many people, in addition, if you have any better ideas, also welcome to share communication ha.
* * – * * END –
Recommended reading
【1】c++nullptr constexpr
【2】 a brief introduction to the software framework of embedded low-level development 【3】 the program in CPU is how to run up the required reading 【4】C++ anonymous function (lambda expression) 【5】 stage article summary analysis
This public account all original dry goods have been sorted into a catalogue, reply [resources] can be obtained.
Reference links:
C++ primer, fifth edition
Blog.csdn.net/shuzfan/art…
www.cnblogs.com/goodhacker/…