About type conversions in C + +

Source: Internet
Author: User

Four types of conversion operators are defined in C + +: static_cast, const_cast, dynamic_cast, and reinterpret_cast.

The usage of static_cast is similar to the coercion type conversion in C, which can convert one type to another type:

Double N;int a=static_cast<int> (n);

Const_cast is used to remove the constant property of a variable and convert a const variable to a non-const variable:

const int A=0;int b=const_cast<int> (a);

Dynamic_cast is used to "transform the pointers or references that point to base class objects into derived or objects that point to pointers class references and know if the transformation was successful." "If the transformation fails, it appears as a null pointer (when the transformed object is a pointer) or a exception (when the transformed object is reference).

Widget *pw;update (dynamic_cast<specialwidget*> (PW)), void Updateviaref (specialwidget& rsw); Updateviaref ( Dynamic_cast<specialwidget&> (*PW));

The conversion result of the reinterpret_cast operator is closely related to the compiler platform, which does not have portability. It can be used to convert pointer types:

typedef void (*MYFUN) (int); void fun1 (int a) {Std::cout<<a<<std::endl;} int fun2 (int a,int c) {Std::cout<<c<<std::endl;return A;} int main () {void (*fun) (int);fun=reinterpret_cast<myfun> (fun2); fun (5); System ("pause"); return 0;}

Because this operator is not portable, in some cases such a transformation may result in incorrect results, so it is not necessary to avoid the function pointer transformation as much as possible.

About type conversions in C + +

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.