【C++】4种强制类型转换|static_cast|dynamic_cast|reinterpret_cast|const_cast---编辑中

目录

C-style cast

1)  static_cast(不带类型检查的转换--编译时)

2)  dynamic_cast(带类型检查的转换--运行时检查)

3)   reinterpret_cast(一种类型的转换为另一种类型--编译时)

4)   const_cast(设置或移除const属性--编译时)

static_cast和reinterpret_cast的区别

四种casting方法的典型用法示例

dynamic_cast 使用示例:


相关讨论贴:C++中4种强制类型转换使用得多吗?-CSDN论坛

static_cast、dynamic_cast、reinterpret_cast和const_cast之间的区别

C-style cast


C-style cast举例:

 int i;
 double d;
 i = (int) d;

在简单的情况下,上面这种类型转换可以很好地工作,但在C++中往往还是不够的,为此ANSI-C++新标准定义的四个转换符,即

static_cast
dynamic_cast
reinterpret_cast
const_cast


同时在C++环境中,原先的C-Style的类型转换仍旧可以使用。


1)  static_cast(不带类型检查的转换--编译时


    用法:static_cast <typeid> (expression)
    说明:该运算符把expression转换为typeid类型,但没有运行时类型检查来确保转换的安全性。
   

用途:
    a) 用于类层次结构中基类和派生类之间指针或者引用的转换。
        up-casting (把派生类的指针或引用转换成基类的指针或者引用表示)是安全的;
        down-casting(把基类指针或引用转换成子类的指针或者引用)是不安全的。
    b) 用于基本数据类型之间的转换,如把int转换成char,这种转换的安全性也要由开发人员来保证。
    c) 可以把空指针转换成目标类型的空指针(null pointer)。
    d) 把任何类型的表达式转换成void类型。
    注意: static_cast不能转换掉expression的const、volitale或者__unaligned属性。


2)  dynamic_cast(带类型检查的转换--运行时检查


    用法:dynamic_cast <typeid> (expression)
    说明:该运算符把expression转换成typeid类型的对象。typeid必须是类的指针、类的引用或者void*

如果typeid是类的指针类型, 那么expression也必须是指针,如果typeid是一个引用,那么expression也必须是一个引用。

一般情况下,dynamic_cast用于具有多态性的类(即有虚函数的类)的类型转换。

dynamic_cast依赖于RTTI信息,其次,在转换时,dynamic_cast会检查转换的source对象是否真的可以转换成target类型, 这种检查不是语法上的,而是真实情况的检查。先看RTTI相关部分,通常,许多编译器都是通过vtable找到对象的RTTI信息的,这也就意味着,如果基类没有虚方法,也就无法判断一个基类指针变量所指对象的真实类型,这时候,dynamic_cast只能 用来做安全的转换,例如从派生类指针转换成基类指针。而这种转换其实并不需要dynamic_cast参与。

也就是说,dynamic_cast是根据RTTI记载的信息来判断类型转换是否合法的。
   

用途:

主要用于类层次之间的up-casting和down-casting,还可以用于类之间的交叉转换。

在进行down-casting时,dynamic_cast具有类型检查的功能,比static_cast更安全。

检测在运行时进行。如果被转换的指针不是一个被请求的有效完整的对象指针, 返回值为NULL。当用于多态类型时,它允许任意的隐式类型转换以及相反过程。不过,与static_cast不同,在后一种情况里
        (注:即隐式转 换的相反过程),dynamic_cast会检查操作是否有效。也就是说,它会检查转换是否会返回一个被请求的有效的完整对象。


    注意:dynamic_cast不能转换掉expression的const、volitale或者__unaligned属性。


3)   reinterpret_cast(一种类型的转换为另一种类型--编译时


     用法:reinterpret_cast <typeid>(expression)
     说明:转换一个指针为其他类型的指针,也允许将一个指针转换为整数类型,反之亦然。这个操作符能够在非相关的类型之间进行转换。操作结果只是简单的从一个指针到别的指针的值的二进制拷贝,在类型之间指向的内容不做任何类型的检查和转换。这是一个强制转换。使用时有很大的风险,慎用之。
     注意:reinterpret_cast不能转换掉expression的const、volitale或者__unaligned属性。


4)   const_cast(设置或移除const属性--编译时


     用法:const_cast<typeid>(expression)
     说明:这个类型操纵传递对象的const属性,或者是设置或者是移除。如:
           Class C{…}
           const C* a = new C;
           C* b = const_cast<C*>(a);
           如果将上面的const_cast转换成其他任何其他的转换,编译都不能通过,出错的信息大致如下:
           “…cannot convert from 'const class C *' to 'class C *'”。

static_cast和reinterpret_cast的区别

C++ primer第五章里写了编译器隐式执行任何类型转换都可由static_cast显式完成;reinterpret_cast通常为操作数的位模式提供较低层的重新解释

1、C++中的static_cast执行非多态的转换,用于代替C中通常的转换操作。因此,被做为显式类型转换使用。比如:

int i;
float f = 166.71;
i = static_cast<int>(f);


2、C++中的reinterpret_cast主要是将数据从一种类型的转换为另一种类型。将数据的二进制存在形式的重新解释。比如:此时结果,i的值为166。

int i;
char *p = "This is an example.";
i = reinterpret_cast<int>(p);

此时结果,i与p的值是完全相同的。reinterpret_cast的作用是说将指针p的值以二进制(位模式)的方式被解释为整型,并赋给i,//i 也是指针,整型指针;一个明显的现象是在转换前后没有数位损失

四种casting方法的典型用法示例

下面的代码是四种casting方法的典型用法示例:
 

     #include <iostream>
     using namespace std;
     class Base
     {
     public:
         int _base;
         virtual void printinfo()
         {
              cout << _base << endl;
         }
     };
     class Derived : public Base
     {
     public:
         int _derived;
         virtual void printinfo()
         {
              cout << _derived << endl;
         }
     };
     int main(void)
     {
         Base    b1;
         Derived d1;
         int    aInt    = 10;
         long   aLong   = 11;
         float  aFloat  = 11.11f;
         double aDouble = 12.12;
         Derived* pd = static_cast<Derived*>(&b1);       // down-casting 不安全
         Base*    pb = static_cast<Base*>(&d1);          // up-casting   安全
         Derived& d = static_cast<Derived&>(b1);         // down-casting 不安全
         Base& b = static_cast<Base&>(d1);               // up-casting   安全
         aInt = static_cast<int>(aFloat);                // 基本数据类型转换
         void* sth = static_cast<void*>(&aDouble);       // 将double指针类型转换成void指针类型
         double* bDouble = static_cast<double*>(sth);    // 将void指针类型转换成double指针类型
         cout << *bDouble << endl;
         Base* pb1 = dynamic_cast<Base*>(&d1);
         //Derived* pd1 = dynamic_cast<Derived*>(&b1);   // 编译时有warning,运行时出错
         int bInt = reinterpret_cast<int>(pb1);          // 将地址或指针转换成整数
         cout << bInt << endl;
         pb1 = reinterpret_cast<Base*>(bInt);            // 将整数转换成地址或指针
         int* cInt = reinterpret_cast<int*>(&aFloat);    // 这个转换的结果会出乎意料
         cout << (int)*cInt << endl;
         const Base* bBase = new Base();
         Base* cBase = const_cast<Base*>(bBase);
         //Base* dBase = dynamic_cast<Base*>(bBase);     // 不能通过编译
         //Base* eBase = static_cast<Base*>(bBase);      // 不能通过编译
         //Base* fBase = reinterpret_cast<Base*>(bBase); // 不能通过编译
         return 0;
    }

dynamic_cast 使用示例:


// testCast.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

class CAnimal
{
public:
    virtual void eat() 
    {
        cout << "animal eat" << endl;
    }

};

class CDog : public CAnimal
{
public:
    void eat()
    {
        cout << "dog eat" << endl;
    }

    void playBone()
    {
        cout << "dog play bone" << endl;
    }
};

class CCat : public CAnimal
{
public:
    void eat()
    {
        cout << "cat eat" << endl;
    }

    void playBall()
    {
        cout << "cat play ball" << endl;
    }
};

int main()
{
    vector<CAnimal*> vecAnimalList;
    CAnimal* pAnimal = new CDog();
    vecAnimalList.push_back(pAnimal);

    pAnimal = new CDog();
    vecAnimalList.push_back(pAnimal);

    pAnimal = new CCat();
    vecAnimalList.push_back(pAnimal);

    pAnimal = new CCat();
    vecAnimalList.push_back(pAnimal);

    for (int nIdx = 0; nIdx < vecAnimalList.size(); ++nIdx)
    {
        vecAnimalList[nIdx]->eat();

        CDog* pDog = dynamic_cast<CDog*>(vecAnimalList[nIdx]);
        if (nullptr != pDog)
        {
            pDog->playBone();
        }
        else
        {
            CCat* pCat = dynamic_cast<CCat*>(vecAnimalList[nIdx]);
            if (nullptr != pCat)
            {
                pCat->playBall();
            }
            else
            {
                cout << "error type" << endl;
            }
        }
    }



    return 0;
}


C++强制类型转换运算符(static_cast、reinterpret_cast、const_cast和dynamic_cast)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值