zoukankan      html  css  js  c++  java
  • 第11课 新型的类型转换

    C语言方式的强制类型转换:

    粗暴的类型转换示例:

     1 #include <stdio.h>
     2 
     3 typedef void(PF)(int);
     4 
     5 struct Point
     6 {
     7     int x;
     8     int y;
     9 };
    10 
    11 int main()
    12 {
    13     int v = 0x12345;
    14     PF* pf = (PF*)v;
    15     char c = char(v);
    16     Point* p = (Point*)v;
    17     
    18     pf(5);
    19     
    20     printf("p->x = %d
    ", p->x);
    21     printf("p->y = %d
    ", p->y);
    22 
    23     return 0;
    24 }

    编译运行结果如下:

     C方式的强制类型转换存在的问题:

    过于粗暴:  

      任意类型之间都可以进行转换,编译器很难判断其正确性

    难于定位:

      在源码中无法快速定位所有使用强制类型转换的语句

     强制类型转换在工程中是很难完全避免的。

    C++将强制类型转换分为四种类型:

    static_cast强制类型转换:

    const_cast强制类型转换:

    reinterpret_cast强制类型转换:

    dynamic_cast:

    强制类型转换示例:

     1 #include <stdio.h>
     2 
     3 void static_cast_demo()
     4 {
     5     int i = 0x12345;
     6     char c = 'c';
     7     int* pi = &i;
     8     char* pc = &c;
     9     
    10     c = static_cast<char>(i);
    11     pc = static_cast<char*>(pi);
    12 }
    13 
    14 void const_cast_demo()
    15 {
    16     const int& j = 1;
    17     int& k = const_cast<int&>(j);
    18     
    19     const int x = 2;
    20     int& y = const_cast<int&>(x);
    21     
    22     int z = const_cast<int>(x);
    23     
    24     k = 5;
    25     
    26     printf("k = %d
    ", k);
    27     printf("j = %d
    ", j);
    28     
    29     y = 8;
    30     
    31     printf("x = %d
    ", x);
    32     printf("y = %d
    ", y);
    33     printf("&x = %p
    ", &x);
    34     printf("&y = %p
    ", &y);
    35 }
    36 
    37 void reinterpret_cast_demo()
    38 {
    39     int i = 0;
    40     char c = 'c';
    41     int* pi = &i;
    42     char* pc = &c;
    43     
    44     pc = reinterpret_cast<char*>(pi);
    45     pi = reinterpret_cast<int*>(pc);
    46     pi = reinterpret_cast<int*>(i);
    47     c = reinterpret_cast<char>(i); 
    48 }
    49 
    50 void dynamic_cast_demo()
    51 {
    52     int i = 0;
    53     int* pi = &i;
    54     char* pc = dynamic_cast<char*>(pi);
    55 }
    56 
    57 int main()
    58 {
    59     static_cast_demo();
    60     const_cast_demo();
    61     reinterpret_cast_demo();
    62     dynamic_cast_demo();
    63     
    64     return 0;
    65 }

    根据我们上面的分析,第11行是错误的,22行是错误的,47行是错误的,54行是错误的。

    小结:

      C方式的强制类型转换:

        过于粗暴

        潜在的问题不易被发现

        不易在代码中定位

      新式类型转换以C++关键字方式出现

        编译器能够帮助检查潜在的问题

        非常方便的在代码中定位

        支持动态类型识别(dynamic_cast)

  • 相关阅读:
    职场中如何沟通 15条技巧现在学
    白领丽人:这六行盛产“钻石王老五”
    个人创业融资中的八大法律问题
    [转帖]用心领导先于理性管理
    职场中牢固人际关系的三十六计
    创业:如何制定最佳融资决策
    工作中如何演绎好你的职场情绪
    怎么成为一个成功的人
    创业不得不看:华商富豪们的成功哲学
    一流简历的10大关注项
  • 原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9527177.html
Copyright © 2011-2022 走看看