首页 > 编程笔记

C++强制类型转换运算符(4种)

与C语言的类型转换相比,C++ 的类型转换机制更加安全。C++ 提供了四个类型转换运算符应对不同类型数据之间的转换,下面分别进行介绍。

1) static_cast<type>(expression)

static_cast<> 是最常用的类型转换运算符,主要执行非多态的转换,用于代替C语言中通常的转换操作。

static_cast<>可以实现下列转换:

使用 static_cast<> 运算符进行类型转换的示例代码如下所示:
int a=1;
float b=3.14;
a=static_cast<int>(b);    //将float类型转换为int类型
b=static_cast<float>(a);  //将int类型转换为float类型
int *q=NULL;
void* p = NULL;
q=p;      //将空指针转换为int类型,C语言允许,C++不允许
p=q;
q=static_cast<int*>(p);   //将空指针转换为int类型指针

2) reinterpret_cast<type>(expression)

reinterpret_cast 通常为操作数的位模式提供较低层的重新解释。

例如,如果将一个 int 类型的数据 a 转换为 double 类型的数据 b,仅仅是将 a 的比特位复制给 b,不作数据转换,也不进行类型检查。reinterpret_cast 要转换的类型必须是指针类型、引用或算术类型。

使用 reinterpret_cast<> 运算符进行类型转换的示例代码具体如下:
char c = 'a';
int d = reinterpret_cast<int&>(c);
int *p=NULL; 
float *q=NULL;
p = q;                                //C 语言允许,C++语言不允许
q = p;                                //C 语言允许,C++语言不允许
p = static_cast<int*>(q);         //static_cast无法转换
q = static_cast<int*>(p);         //static_cast无法转换
p = reinterpret_cast<int*>(q);
q = reinterpret_cast<float*>(p)

3) const_cast<type>(expression)

const_cast<> 用于移除 const 对象的引用或指针具有的常量性质,可以去除 const 对引用和指针的限定。示例代码如下所示:
int num = 100;
const int* p1 = &num;
//将常量指针转换为普通类型指针,去除const属性
int* p2 = const_cast<int*>(p1);
*p2 = 200;
int a=100;
const int & ra=a;
//将常量引用转换为普通类型引用,去除const属性
const_cast<int&>(ra)=200;
需要注意的是,const_cast<> 只能用于转换指针或引用。

4) dynamic_cast<type>(expression)

dynam ic_cast<> 用于运行时检查类型转换是否安全,可以在程序运行期间确定数据类型,如类的指针、类的引用和 void*。

dynam ic_cast<>主要应用于类层次间的向上转换和向下转换,以及类之间的交叉转换。

在类层次间进行向上转换时,它和 static_cast 作用一致。不过,与 static_cast 相比,dynam ic_cast 能够在运行时检查类型转换是否安全。

当向下转换时,如果基类指针或引用指向派生类对象,dynam ic_cast 运算符会返回转换后类型的指针,这样的转换是安全的。如果基类指针或引用没有指向派生类对象,则转换是不安全的,转换失败时就返回 NULL。

优秀文章