Forced type conversion between c and c ++

Source: Internet
Author: User

We know that there is only one type conversion in C language,

TYPE B = (TYPE);

In c ++, the conversion types are subdivided into three display type conversion symbols: static_cast, const_cast, and reinterpret_cast. This type of display conversion provides richer meanings and functions, A better type check mechanism facilitates code maintenance.

  • It is mainly used for conversion between related types, such as char, int, and double data types of c, and conversion between the base class and sub-class (without dynamic_cast security). There may be byte conversion, irrelevant types such as int * and double * cannot be converted, and class pointers without inheritance relationships
  • Conversion between void * and other types of pointers
 bv =  i = ()bv;   iv2 = static_cast<>(bv);  iv2 = reinterpret_cast<>(bv);  bv =  *pbv = & *iv1 = (*)pbv;  *iv2 = static_cast<*>(pbv);  *iv2 = reinterpret_cast<*>(pbv);  *piv1 = (* *piv2 = static_cast<*> *piv3 = static_cast<*>(piv2); 

  • The type to be converted must be a pointer or reference. Only the converted type can be used to re-interpret the bytes.
  • If you convert a non-pointer variable to a pointer, the variable size must be equal to the pointer size.
  • Poor portability
 lv =   llv = *piv1 = (*)lv;   *piv2 = reinterpret_cast<*>= reinterpret_cast<*>(llv); 

Remove pointer or referenced const or volatile attributes

  const_char =  *pch = &const_char;   *pch = (*)&const_char; *pch =   const_char =  chv = const_cast<>  *pch = & *chv = const_cast<*>(&const_char);*chv=’c’;

Summary: The forced type conversion symbols corresponding to the three types of c are all determined during compilation. The dynamic_cast of RTTI has nothing to do with c and will be introduced later.

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.