Four types of C + + type conversion operators

Source: Internet
Author: User

One, C style type conversion operator

(type) expression

Example:

int Firstnumber, secondnumber;double result = ((double) firstnumber)/secondnumber;


Ii. C + + type conversion operators

1.static_cast is basically functionally as powerful as the C-style type conversion, meaning the same.

Double result = static_cast<double> (firstnumber)/secondnumber;

It also has functional limitations. For example, you cannot convert a struct to an int type or convert a double type to a pointer type using static_cast like a C-style type conversion, and static_cast cannot remove the const attribute from an expression because another new type conversion operator Const_cast has such a feature.

2.const_cast The const or volatileness attribute that is used for type-cast-off expressions. By using const_cast, you emphasize to people and compilers that what you want to do with a type conversion is just a constness or volatileness property that changes something.

Class Widget {...}; Class Specialwidget:public Widget {...}; void Update (Specialwidget *PSW); specialwidget SW; SW is a non-const object. Const specialwidget& CSW = SW; CSW is a reference to SW//It is a Const object update (&CSW); Error! Cannot pass a const specialwidget* variable//to a function that handles specialwidget* type variable update (const_cast<specialwidget*> (&CSW)) ; correctly, the CSW const is shown to be converted (//CSW and SW Two variable values can be updated in the update//function) update ((specialwidget*) &CSW); Ditto, but with a more difficult to identify//C-style type conversion widget *PW = new Specialwidget;update (PW); Error! The type of PW is widget*, but the//update function handles the specialwidget* type update (const_cast<specialwidget*> (PW)); Error! Const_cast can only be used in places that affect//constness or volatileness. ,//cannot be used for type conversions to inheriting subclasses.

Obviously, the most common use of const_cast is to remove the constants of an object.

3.dynamic_castUsed to safely move down type conversions along the inheritance of a class. That is, you can use dynamic_cast pointer or reference to the base class to convert exponentially to its derived class or its sibling class, and you can know whether the conversion succeeded. The failed transformation returns a null pointer (when the pointer is type-cast) or throws an exception (when the reference is type-converted)
Widget *pw;...update (dynamic_cast<specialwidget*> (PW)); Correct, pass to the update function a pointer//is a pointer to a PW that has a variable type of specialwidget//If PW does point to an object,//Otherwise pass past will make null pointer. void Updateviaref (specialwidget& rsw); Updateviaref (dynamic_cast<specialwidget&> (*PW)); That's right. Pass to the UPDATEVIAREF function//specialwidget PW pointer, if PW//Does point to an object//otherwise throws an exception
Dynamic_casts is limited in helping you navigate the inheritance hierarchy. It cannot be used on a type that lacks a virtual function (see clause M24), nor does it use it to convert constness.
int Firstnumber, secondnumber;double result = dynamic_cast<double> (firstnumber)/secondnumber; Error! No inheritance Relationship const Specialwidget sw;update (dynamic_cast<specialwidget*> (&SW)); Error! DYNAMIC_CAST cannot convert the const.
4.reinterpret_castAlmost all of the conversion results are defined by the execution period (implementation-defined. Therefore, code that uses reinterpret_casts is difficult to port. The most common use of reinterpret_casts is to convert between function pointer types.

For example, suppose you have an array of function pointers:

typedef void (*FUNCPTR) (); Funcptr is a pointer to a function that has no parameters and returns a value of type voidfuncptr funcptrarray[10]; Funcptrarray is an array that can hold 10 funcptrs pointers
Let's assume you want (for some inexplicable reason) to put a pointer to the following function into the funcptrarray array: int dosomething ();
You can't just do this by typing, because the dosomething function has an incorrect type for the Funcptrarray array. The function return value in the Funcptrarray array is type void, and the DoSomething function return value is of type int.
Funcptrarray[0] = &doSomething; Error! Types do not match
Reinterpret_cast allows you to force the compiler to look at them in your own way:
FUNCPTRARRAY[0] =//This compiles reinterpret_cast<funcptr> (&dosomething);

The code for the conversion function pointer is not portable (c + + does not guarantee that all function pointers are represented in the same way), and in some cases such conversions produce incorrect results (see clause M31), so you should avoid converting function pointer types.


Iii. Summary

A summary is:

Static_cast and C-style forced type conversions are similar, except that structs cannot be converted to int and double to pointer type.

Const_cast is used to change the const and Volatileness properties, and it is common to remove the const attribute (convert the const object to non-const);

Dynamic_cast is used for the downward conversion of class inheritance relationships, but cannot be used for types lacking virtual functions;

The conversion result of the reinterpret_cast is defined by the execution period.


Reference: more effective C + + clause 2: Try to use C + + style type conversions

Related: C + + type conversion and Rtti

Four types of C + + type conversion operators

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.