c++类型转换

来源:互联网 发布:java第三方支付接口 编辑:程序博客网 时间:2024/06/12 01:05

本文转载自Jiang's C++ Space 和goodhacker


1、指针=>常规类型


比如我们需要打印一个指针的值(它指向的地址)的时候,我们指针直接转换为整数,用printf输出个16进制的地址。我们可以用旧式转换,或者reinterpret_cast,其它转换都是不可以的。
    CIndepend oIndepend;
    CIndepend * pIndepend = &oIndepend;
    unsigned char cTest= (unsigned char )pIndepend;
    unsigned short sTest = (unsigned short )pIndepend;
    unsigned int iTest = (unsigned int )pIndepend;

在32位系统中,指针其实是个32位的无符号整型,要正常输出指针的值,正确做法是把它转换为一个无符号32位整形数输出(有符号的可能导致输出不正确),如果转换为一个16位的,或者8位的,那将丢失数据,当然了,前面这段代码不会出现任何error和warning,你知道你在干什么即可。刚说了,我们除了旧式转换还可以用reinterpret_cast,于是上面的代码可以这样写:
    unsigned char cTest= reinterpret_cast<unsigned char >(pIndepend);
    unsigned short sTest = reinterpret_cast<unsigned short>(pIndepend);
    unsigned int iTest = reinterpret_cast<unsigned int>(pIndepend);

也是没有任何问题的,运行效果一样,那我们能不能把指针转换为浮点型呢?这样:
    float fTest = reinterpret_cast<float>(pIndepend);
    double dTest = reinterpret_cast<double>(pIndepend);

不行,你试试看就知道了,你会得到这样的编译错误:

error C2440: 'reinterpret_cast' : cannot convert from 'class CIndepend *' to 'float'
        There is no context in which this conversion is possible
error C2440: 'reinterpret_cast' : cannot convert from 'class CIndepend *' to 'double'
        There is no context in which this conversion is possible

其实将指针转换为浮点数这种做法就很怪异嘛,你不觉得吗?这样有什么用啊?不过你一定要这样干的话也不是没有办法,看代码:
    float fTest = reinterpret_cast<float &>(pIndepend);
    double dTest = reinterpret_cast<double &>(pIndepend);

加个小小的“&”符号就可以了,C++会不顾一切地把pIndepend这个变量当作一个float和double,把指针的值“理解”为float和double,当然,这样获得的浮点数的值是没什么实际意义的,因为指针的值是32位无符号整型,而浮点数有它自己特定的格式,这么一转换就牛头不对马嘴。你还可以这样写:
      float fTest = (float &)pIndepend;
      double dTest = (double &)pIndepend;

效果一样,得到的也是无意义的值。

2、常规类型=>指针

就是反过来罗,可能不说大家都能猜到结果了。把常规类型转换为指针有什么用呢?可能有点用,比如我们在某些特殊的场合要求一个指针指向一个特别的地址,这时候我们可以直接给指针赋个值,当然了,这个值应该是整型:
    CIndepend * pIndepend;

    char cVal = 1;
    short sVal = 2;
    int iVal = 3;

    pIndepend = (CIndepend *)cVal;
    pIndepend = (CIndepend *)sVal;
    pIndepend = (CIndepend *)iVal;

这样是没问题的,那浮点数呢?——又来了,浮点数转换为指针?这怎么算啊?显然这是不行的,如果真的需要“转换”,那就先把浮点数转换为整型,然后再赋值给指针吧。这个时候,dynamic_cast和static_cast都是不行的。

3、基本类型转换

比如int转换为float,char转变为short,很多时候我们都“默认”了这种转换,即使没有显式指定用旧式转换还是static_cast。在这种类型的转换中,旧式转换和static_cast的表现非常地类似:
    double dVal = 5.0;

    char cVal = static_cast<char>(dVal);
    short sVal = static_cast<short>(dVal);
    int iVal = static_cast<int>(dVal);

    cVal = (char)(dVal);
    sVal = (short)(dVal);
    iVal = (int)(dVal);

而dynamic_cast还是不可行,那……reinterpret_cast呢?不妨试试看:
    double dVal = 5.0;

    char cVal = reinterpret_cast<char>(dVal);
    short sVal = reinterpret_cast<short>(dVal);
    int iVal = reinterpret_cast<int>(dVal);

一编译,就出下面的错误:

error C2440: 'reinterpret_cast' : cannot convert from 'double' to 'char'
        Conversion is a valid standard conversion, which can be performed implicitly or by use of static_cast, C-style cast or function-style cast
error C2440: 'reinterpret_cast' : cannot convert from 'double' to 'short'
        Conversion is a valid standard conversion, which can be performed implicitly or by use of static_cast, C-style cast or function-style cast
error C2440: 'reinterpret_cast' : cannot convert from 'double' to 'int'
        Conversion is a valid standard conversion, which can be performed implicitly or by use of static_cast, C-style cast or function-style cast

说这是个有效标准转换,请使用static_cast或者C风格的旧式转换。reinterpret_cast不是号称最宽松的转换么?怎么不行了?你一定要它行也是没问题的,和前面的那样,加个“&”符号:
    char cVal = reinterpret_cast<char &>(dVal);
    short sVal = reinterpret_cast<short &>(dVal);
    int iVal = reinterpret_cast<int &>(dVal);

但结果并不是你想要的结果,因为这样reinterpret_cast会不管三七二十一,直接把dVal的东西当作是一个char,short和int,很明显,double是有一定的格式的,将double直接“理解”为char,short或者int一定会有问题。

4、class的转换

上一节说的是基本类型,那对于类呢?一个类直接转换为另一个类,这看起来确实有些荒谬,不过强大而灵活的C++却偏偏允许了这种行为。看代码:
class CBase
{
public:
    CBase(){};
    int m_iBase;
};

class CIndepend
{
public:
    CIndepend(){};
    int m_iIndepend;
};

int main(int argc, char* argv[])
{
    CBase oBase;
    CIndepend oIndepend = reinterpret_cast<CIndepend &>(oBase);
    return 0;
}

居然编译过去了,运行貌似也没什么问题,当然转换过程和前面的差不多,就是把oBase理解为一个CIndepend对象,这个赋值运算执行“位拷贝”,这种方式的转换在实际中是碰不到的,起码我想不出有什么理由使用它。这种情况下,其它的转换方式都是不可行的。

5、class=>指针 or 指针=>class

这种行为更怪异,class直接理解为指针?这其实是不可行的,跟前面提到的浮点数转换为指针一样,如果实在需要,就把class转变为整型,然后整型转换为指针:
CIndepend * pIndepend = reinterpret_cast<CIndepend *>(reinterpret_cast<unsigned int &>(oBase));

可这……这啥意思呢?哈哈,别问我。反过来,指针转换为class恐怕也令人费解:
    CDerived oDerived;
    CDerived *pDerived = &oDerived;
    CIndepend oIndepend = reinterpret_cast<CIndepend &>(pDerived);

能担当起这种怪异的工作的,唯reinterpret_cast是也,这样会产生什么后果呢?指针是个32位无符号整型,将它强制理解为一个CIndepend,然后作位拷贝,理所当然,oIndepend的值会被改变,而且还有访问越界的风险,导致内容混乱甚至程序崩溃。

6、指针之间的转换

前面一直没提起的一种转换就是dynamic_cast,因为它是最为严格的一种转换,它只能完成指针到指针的转换,而且还有限制。看这个:
    CDerived oDerived;
    CDerived *pDerived = &oDerived;
    CIndepend *pIndepend = dynamic_cast<CIndepend *>(pDerived);

编译出错了:

error C2683: dynamic_cast : 'CDerived' is not a polymorphic type
        D:\work\CastTest\CastTest.cpp(13) : see declaration of 'CDerived'

因为CDerived和CIndepend没有继承关系,把dynamic_cast换成static_cast还是不行的,会出另外一个错:

error C2440: 'static_cast' : cannot convert from 'class CDerived *' to 'class CIndepend *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

编译器说这是没有关系的两个指针,应该用reinterpret_cast或者C风格的旧式转换,再看:
    //CDerived是CBase的子类
    CBase oBase;
    CBase *pBase = &oBase;
    CDerived *pDerived = dynamic_cast<CDerived *>(pBase);

基类指针转换为子类指针,行不行呢?出错,错误跟刚才的一样,记住,dynamic_cast仅仅可以把子类指针转换为基类指针,别的都不行!上面这段代码如果不用dynamic_cast,而是用static_cast,就能编译通过,static_cast的要求来得比较宽松。


C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是:
TYPE b = (TYPE)a。
C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。

const_cast,字面上理解就是去const属性。
static_cast,命名上理解是静态类型转换。如int转换成char。
dynamic_cast,命名上理解是动态类型转换。如子类和父类之间的多态类型转换。
reinterpret_cast,仅仅重新解释类型,但没有进行二进制的转换。
4种类型转换的格式,如:TYPE B = static_cast(TYPE)(a)。

const_cast
去掉类型的const或volatile属性。
复制代码

1 struct SA {
2 int i;
3 };
4 const SA ra;
5 //ra.i = 10; //直接修改const类型,编译错误
6 SA &rb = const_cast<SA&>(ra);
7 rb.i =10;

复制代码

static_cast

类似于C风格的强制转换。无条件转换,静态类型转换。用于:
1. 基类和子类之间转换:其中子类指针转换成父类指针是安全的;但父类指针转换成子类指针是不安全的。(基类和子类之间的动态类型转换建议用dynamic_cast)
2. 基本数据类型转换。enum, struct, int, char, float等。static_cast不能进行无关类型(如非基类和子类)指针之间的转换。
3. 把空指针转换成目标类型的空指针。
4. 把任何类型的表达式转换成void类型。
5. static_cast不能去掉类型的const、volitale属性(用const_cast)。

1 int n =6;
2 double d = static_cast<double>(n); // 基本类型转换
3 int*pn =&n;
4 double*d = static_cast<double*>(&n) //无关类型指针转换,编译错误
5 void*p = static_cast<void*>(pn); //任意类型转换成void类型

dynamic_cast
有条件转换,动态类型转换,运行时类型安全检查(转换失败返回NULL):
1. 安全的基类和子类之间转换。
2. 必须要有虚函数。
3. 相同基类不同子类之间的交叉转换。但结果是NULL。
复制代码

 1 class BaseClass {
 2 public:
 3 int m_iNum;
 4 virtualvoid foo(){}; //基类必须有虚函数。保持多台特性才能使用dynamic_cast
 5 };
 6
 7 class DerivedClass: public BaseClass {
 8 public:
 9 char*m_szName[100];
10 void bar(){};
11 };
12
13 BaseClass* pb =new DerivedClass();
14 DerivedClass *pd1 = static_cast<DerivedClass *>(pb); //子类->父类,静态类型转换,正确但不推荐
15 DerivedClass *pd2 = dynamic_cast<DerivedClass *>(pb); //子类->父类,动态类型转换,正确
16
17 BaseClass* pb2 =new BaseClass();
18 DerivedClass *pd21 = static_cast<DerivedClass *>(pb2); //父类->子类,静态类型转换,危险!访问子类m_szName成员越界
19 DerivedClass *pd22 = dynamic_cast<DerivedClass *>(pb2); //父类->子类,动态类型转换,安全的。结果是NULL

复制代码

reinterpret_cast
仅仅重新解释类型,但没有进行二进制的转换:
1. 转换的类型必须是一个指针、引用、算术类型、函数指针或者成员指针。
2. 在比特位级别上进行转换。它可以把一个指针转换成一个整数,也可以把一个整数转换成一个指针(先把一个指针转换成一个整数,在把该整数转换成原类型的指针,还可以得到原先的指针值)。但不能将非32bit的实例转成指针。
3. 最普通的用途就是在函数指针类型之间进行转换。
4. 很难保证移植性。

1 int doSomething(){return0;};
2 typedef void(*FuncPtr)(); //FuncPtr is 一个指向函数的指针,该函数没有参数,返回值类型为 void
3 FuncPtr funcPtrArray[10]; //10个FuncPtrs指针的数组 让我们假设你希望(因为某些莫名其妙的原因)把一个指向下面函数的指针存入funcPtrArray数组:
4
5 funcPtrArray[0] =&doSomething;// 编译错误!类型不匹配,reinterpret_cast可以让编译器以你的方法去看待它们:funcPtrArray
6 funcPtrArray[0] = reinterpret_cast<FuncPtr>(&doSomething); //不同函数指针类型之间进行转换

总结
去const属性用const_cast。
基本类型转换用static_cast。
多态类之间的类型转换用daynamic_cast。
不同类型的指针类型转换用reinterpret_cast。

原创粉丝点击