第11课-新型的类型转换

1. 强制类型转换

  • C方式的强制类型转换

    - (Type)(Expression)

    - Type(Expression)

typedef void(PF)(int);

struct Point
{
  int x;
  int y;
};

int v = 0x12345;
PF* pf = (PF*)v
char c = char(v);
Point* p = (Point*)v;
  • C方式强制类型转换存在的问题

    - 过于粗暴

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

    - 难于定位

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

 

问题。。。

强制类型转换在实际工程中是很难完全避免的!如何进行更加安全可靠的转换?

 

2. 新式类型转换

  • C++将强制类型转换分为4种不同的类型

 

 

 用法:xxx_cast<Type>(Expression);

 

  • static_cast强制类型转换

    - 用于基本类型间的转换

    - 不能用于基本类型指针间的转换

    - 用于有继承关系类对象之间的转换和类指针之间的转换

 

  • const_cast强制类型转换

    - 用于去除变量的只读属性

    - 强制转换的目标类型必须是指针引用

 

  • reinterpret_cast强制类型转换

    - 用于指针类型间的强制转换

    - 用于整数指针类型间的强制转换

 

  • dynamic_cast强制类型转换

    - 用于有继承关系的类指针间的转换

    - 用于有交叉关系的类指针间的转换

    - 具有类型检查的功能

    - 需要虚函数的支持

#include <stdio.h>

void static_cast_demo()
{
    int i = 0x1234;
    char c = 'c';
    int* pi = &i;
    char* pc = &c;
    
    c = static_cast<char>(i);
    //pc = static_cast<char*>(pi);    // error
}

void const_cast_demo()
{
    const int& j = 1;
    int& k = const_cast<int&>(j);
    
    const int x = 2;
    int& y = const_cast<int&>(x);
    //int z = const_cast<int>(x);    // error
    
    k = 5;
    
    printf("k = %d\n", k);    // k = 5
    printf("j = %d\n", j);    // j = 5
    
    y = 8;
    
    printf("x = %d\n", x);       // x = 2
    printf("y = %d\n", y);       // y = 8
    printf("&x = %p\n", &x);   // &x = 0xbfb592e0    
    printf("&y = %p\n", &y);   // &y = 0xbfb592e0
}

void reinterpret_cast_demo()
{
    int i = 0;
    char c = 'c';
    int* pi = &i;
    char* pc = &c;
    
    pc = reinterpret_cast<char*>(pi);
    pi = reinterpret_cast<int*>(pc);
    pi = reinterpret_cast<int*>(i);
    //c = reinterpret_cast<char>(i);        // errro
}

void dynamic_cast_demo()
{
    int i = 0;
    int* pi = &i;
    //char* pc = dynamic_cast<char*>(pi);    // error
}

int main()
{
    static_cast_demo();
    const_cast_demo();
    reinterpret_cast_demo();
    dynamic_cast_demo();
    
    return 0;
}

 

3. 小结

  • C方式的强制类型转换

    - 过于粗暴

    - 潜在的问题不易被发觉

    - 不易在代码中定位

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

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

    - 非常方便的在代码中定位

    - 支持动态类型识别dynamic_cast

 

本文出处:狄泰软件学院

posted @ 2020-03-24 21:27  WisdomMan  阅读(2)  评论(0)    收藏  举报