浅谈C++的类型转换

jopen 10年前

C++是强类型语言,也就是说,变量在使用前就要声明数据类型,不同数据类型分配的内存空间大小也是不同,在转换类型时要注意这个问题,防止数据丢失或越界溢出。文章将简单讨论一下C++的类型转换。

C++从C发展而来,也继承两种C风格的转换:隐式转换和显式转换。

隐式转换
隐式转换是指由编译系统自动进行,不需要人工干预的类型转换,例如:

short a = 2000;  int b;  b = a;
隐式转换,也包括构造函数和运算符的转换,例如:
class A {};  class B {  public:      B (A a) {}  };    A a;  B b = a;
显式转换

和隐式转换相反,显式转换要利用强制类型转换运算符进行转换,例如:

double x = 10.3;  int y;  y = int (x);    // 函数式写法  y = (int) x;    // C风格写法

以上类型转换已经满足了基本类型的转换了。但是如果想转换类和指针,有时代码可以编译,在运行过程中会出错。例如:
#include <iostream>    class CDummy {      float i,j;  public:      CDummy () { i=1; j=1; }  };    class CAddition {      int x,y;  public:      CAddition () { x=1; y=1; }      int result() { return x+y;}  };    int main () {    CDummy d;    CAddition * padd;    padd = (CAddition*) &d;    std::cout << padd->result();    return 0;  }
这段代码会在运行期出错,在执行padd->result()时发生异常,有些编译器会异常退出。
传统明确的类型转换,可以转换成任何其他指针类型任何指针,它们指向的类型无关。在随后的调用成员的结果,会产生一个运行时错误或意外的结果。
/********  无情的分割线 ********* /     作者:没有开花的树     博客:blog.csdn.net/mycwq   / *******   无情的copy  *********/  

C++标准转换运算符
传统的类和指针的类型转换方式很不安全,可能会在运行时异常退出,标准C++ 提供了四个转换运算符:dynamic_cast、reinterpret_cast、static_cast、 const_cast
dynamic_cast <new_type> (expression)  reinterpret_cast <new_type> (expression)  static_cast <new_type> (expression)  const_cast <new_type> (expression)

dynamic_cast
dynamic_cast只能用于指针和引用的对象。其目的是确保类型转换的结果是一个有效的完成所请求的类的对象,所以当我们从一个类转换到这个类的父类,dynamic_cast总是可以成功。dynamic_cast 可以转换NULL指针为不相关的类,也可以任何类型的指针为void指针。 
class CBase { };  class CDerived: public CBase { };  CBase b;  CDerived d;    CBase* pb = dynamic_cast<CBase*>(&d);        // 子类转父类,正确  CDerived* pd = dynamic_cast<CDerived*>(&b);  // 父类转子类,错误
当新的类型不是被转换的类型的父类,dynamic_cast无法完成指针的转换,返回NULL。当dynamic_cast转换引用类型时,遇到失败会抛出Bad_cast 异常。

 

static_cast
static_cast可以执行相关的类的指针之间的转换,可以在子类和父类之间相互转换,但父类指针转成子类指针是不安全的。static_cast没有在运行时进行安全检查,因此我们要先确保转换是安全的。另一方面,static_cast对比dynamic_cast少了在类型安全检查的开销。
class CBase {};  class CDerived: public CBase {};  CBase * a = new CBase;  CDerived * b = static_cast<CDerived*>(a);
上述代码是合法的,b指向一个不完整的对象,可能在运行期导致错误。
static_cast也可以用来执行任何其他非指针的转换,如基本类型enum, struct, int, char, float等之间的标准转换:
double d = 3.14159265;  int i = static_cast<int>(d);   void* p = static_cast<void*>(&i); //任意类型转换成void类型

 

reinterpret_cast
reinterpret_cast转换成任何其他指针类型,甚至无关的类,任何指针类型。操作的结果是重新解释类型,但没有进行二进制的转换。所有的指针转换是允许的:不管是指针指向的内容还是指针本身的类型。
class A {};  class B {};  A * a = new A;  B * b = reinterpret_cast<B*>(a)

reinterpret_cast还可以用来转换函数指针类型,例如:

typedef void(*Func)();                 // 声明一种函数指针定义,返回void  Func pFunc;                            // 定义FuncPtr类型的数组    pFunc = &test;                         // 编译错误!类型不匹配  pFunc = reinterpret_cast<Func>(&test); // 编译成功!转换函数指针类型

const_cast
const_cast用于操纵对象的常量性,去掉类型的const或volatile属性。
#include <iostream>    void print (char * str){    std::cout << str ;  }    int main () {    const char* c = "hello world";    print ( const_cast<char *> (c) );    return 0;  }

参考:

http://blog.csdn.net/mycwq/article/details/17300973
http://www.cnblogs.com/ggjucheng/archive/2012/01/04/2311650.html
http://www.cplusplus.com/doc/tutorial/typecasting/
来自:http://blog.csdn.net/mycwq/article/details/17300973