Some forced type conversions in C + +

Source: Internet
Author: User

In C language, some forced type conversions are often seen, mainly in front of variable names (types). In C + +, there are some differences with C language, there are four types of forced type conversion in C + +.

    1. Static_cast Its main transformation is the conversion between the relevant types


      int main ()

      {

      float a = 1.2;

      int B = static_cast<int> (a);

      cout << b << Endl;

      GetChar ();

      return 0;

      }

2.reinterpret_cast Its main transformation is the conversion between unrelated types

int main ()

{

int a = 1;

int *p = &a;

int b = reinterpret_cast<int> (p);

cout << b << Endl;

GetChar ();

return 0;

}

3.const_cast is a variable that unlocks the const type so that it can change the value of the variable

int main ()

{

volatile const int a = 1;

int *p = Const_cast<int *> (&a);

*p = 2;

cout << a << Endl;

GetChar ();

return 0;

}

4.dynamic_cast is a dynamic transformation, it mainly functions: 1. Can only be used for classes containing virtual functions 2. First check whether the conversion is successful, if the conversion is successful, if not return 0

Class A

{

Public

int _a;

virtual void Show ()

{}

};

Class B:p ublic A

{

Public

int _b;

};

void Test ()

{

A;

b b;

B *PB =dynamic_cast<b *> (&a);

cout << PB << Endl;

}

int main ()

{

Test ();

GetChar ();

return 0;

}


Some forced 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.