dynamic_cast, reinterpret_cast, static_cast and const_cast
在C语言中,经常会遇到类型转换的一些东西。类型转换分为:显示类型转换和隐式类型转换。
隐式类型转换:
所谓隐式类型转换就是语言本身,使用编译器,自动就给我们转成了我们需要的类型
比如如下代码:
short a=2000;
int b;
b=a;
但是要主要一点,数据类型转换,可以低长度的转换成高长度的,否则会丢失数据,出现意想不到的问题。
显示类型转换:
在c语言里,我们使用
short a=2000;
int b;
b = (int) a; // c-like cast notation
b = int (a); // functional notation
但是在c++中,我们使用显示类型转换使用了如下四个关键字
dynamic_cast, reinterpret_cast, static_cast and const_cast
使用方法,如
dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)
尖括号里是我们想要expression转换而成的类型。
他们都各司其职,在不同的语义环境下使用,
1.dynamic_cast
只能使用在类的指针或者引用之上。因此我们使用它子类转换成父类时候使用
如下例子:
class CBase { };
class CDerived: public CBase { };
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = dynamic_cast<CBase*>(&d); // 可以: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // 错误: base-to-derived
完成实现
// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;
class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };
int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;
pd = dynamic_cast<CDerived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast" << endl;
pd = dynamic_cast<CDerived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast" << endl;
} catch (exception& e) {cout << "Exception: " << e.what();}
return 0;
}
从以上例子可以看到,成功转换是返回其地址,如果没成功,就返回一个0值。
2.static_cast
常量性的转换,比如我们可以将int转换成float类型,将父类转换成子类的类型。但是这个并不在运行时检查类型安全,类型安全取决于程序员。
class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast<CDerived*>(a);
double d=3.14159265;
int i = static_cast<int>(d);
3.const_cast
This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:
解除常量性变量。
// const_cast
#include <iostream>
using namespace std;
void print (char * str)
{
cout << str << endl;
}
int main () {
const char * c = "sample text";
print ( const_cast<char *> (c) );
return 0;
}
可以可以正常输出。并不会报编译异常
4.reinterpret_cast
像低级类型转换。
reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.
class A {};
class B {};
A * a = new A;
B * b = reinterpret_cast<B*>(a);
最后,想说的是,不建议使用强制类型转换,Effective c++ 条款27:尽量少做转型动作。
更多文章,欢迎访问:http://blog.csdn.net/wallwind,转载请注明出处