C++强制转换

C风格强制类型转换

C风格的强制类型转换格式

TYPE EXPRESSION1 = (TYPE) EXPRESSION2;

C风格强制类型转换的缺点

  - C风格没有区分类型之间的不同,有时候使用是不合适的
    - 将一个指向const对象的指针转换为指向非const对象的指针
    - 将一个指向基类对象的指针转换成指向一个派生类对象的指针
  - C风格的转换不容易查找,它由一个括号加上一个标识符组成,这样的形式在C++中有很多

C++风格强制类型转换

static_cast

#include <iostream>

using std::cout;
using std::endl;

int main()
{
  int i = 100;
  float f = 0;
  cout << "i = " << i << endl;
  cout << "f = " << f << endl;

  //将一种数据类型转化成另一种数据类型
  f = static_cast<float>(i);
  cout << "i = " << i << endl;
  cout << "f = " << f << endl;

  //指针类型之间的转换
  void *pVoid = malloc(sizeof(int));
  int *pInt = static_cast<int *>(pVoid);
  *pInt = 1;
  cout << "*pInt = " << *pInt << endl;

  return 0;
}
static_cast的用法
  - 用于基本数据类型之间的转换
  - 把void指针转换成目标类型的指针,但不安全
  - 把任何类型的表达式转换成void类型
  - 用于类层次结构中基类和派生类之间指针或引用的转换
    - 进行上行转换(把派生类的指针或引用装换成基类指针或引用)是安全的
    - 进行下行转换(把基类指针或引用转换成派生类的指针或引用)时,没有动态类型检查,是不安全的

const_cast

#include <iostream>

using std::cout;
using std::endl;

int main()
{
  //const_cast用来修改类型的const属性
  const int number = 10;
  //常量指针被转换成非常量指针,并且指向原来的对象
  //常量引用被转换成非常量引用,并且指向原来的对象
  //常量对象被转换成非常量对象
  int *pInt = const_cast<int *>(&number);

  cout << "number = " << number << endl;
  cout << "*pInt = " << *pInt << endl;
  printf("number's address : %p
", &number);
  printf("pInt's address : %p
", pInt);
  
  *pInt = 20;//未定义的行为
  
  cout << "number = " << number << endl;
  cout << "*pInt = " << *pInt << endl;
  printf("number's address : %p
", &number);
  printf("pInt's address : %p
", pInt);
  return 0;
}

dynamic_cast

  该运算符主要用于基类和派生类间的转换,尤其是向下转型的用法中。

reinterpret_cast

  该运算符可以用来处理无关类型之间的转换,即用在任意指针(或引用)类型之间的转换,以及指针与足够大的整数类型之间的转换。
  由此可以看出,reinterpret_cast的效果很强大,但错误的使用reinterpret_cast很容易导致程序的不安全,只有将转换后的类型值转换回到其原始类型,这样才是正确使用reinterpret_cast方式。
原文地址:https://www.cnblogs.com/xkyrl/p/14663146.html