[009]类型转换

一、隐式转换

规则:

a.混合类型的表达式中,其操作数被转为相同的类型

b.用作条件的表达式被转为bool类型

c.用一表达式初始化某个变量,或将一表达式赋值给某个变量,则该表达式被转换为该变量的类型

二、显示转换(强制类型转换)

1.为什么要进行强制类型转换?

   a.需要覆盖通常的标准转换

   b.可能存在多种转换,需要选择一种特定的转换方式

2.转换形式:

      cast-name<type>(expression);

   cast-name根据情况的不同,又分为static_cast、dynamic_cast、const_cast 和 reinterpret_cast。

   ◆static_cast

      ・编译器隐式执行的任何类型转换都可以用static_cast显示完成。

      ・需要将一个较大的数据类型赋值给较小的类型时使用。

      ・可以将存放在void*中的指针值强制转换为原来的指针类型。

double i = 3.14;
void*p = &i;
double *pd = static_cast<double*>(p);

   ◆dynamic_cast

      暂不做论述

   ◆const_cast

      ・去除原本的const属性

const int* p = 0;
int* pi = const_cast<int*>(p);

   ◆reinterpret_cast

      ・为操作数的位模式提供较低层次的重新解释

int *p = 0;
char *pc = reinterpret_cast<char*>(p);

 pc所指向的真实对象是int型,而非字符数组,如果用pc去初始化string对象,则会错误:

string str(pc);

3.旧式强制转换:

type (expr); // Function-style cast notation  
(type) expr; // C-language-style cast notation  

比如:

int i;
double j;
int *p;
char* pc = (char*)p;
int i = int (j);

三、具体的转换例子:

const string*ps;
void *pv;
如果要实现:
pv = (void*)ps;
我们可以使用强制转换:
pv = static_cast<void*>(const_cast<string*>(ps));
原文地址:https://www.cnblogs.com/hustcser/p/3638310.html