栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++强制类型转换

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++强制类型转换

强制类型转换

静态转换(static_cast)

动态转换(dynamic_cast)

常量转换(const_cast)

重新解释转换(reinterpret_cast)


静态转换(static_cast) 用于基础类型转换

如把int转换成char。这种转换的安全也要开发人员来保证

  char a = 'a';
  double d = static_cast(a); //char->double
类层次结构中基类和派生类之间指针或引用的转换
进行上行转换(把派生类的指针或引用转换成基类表示)是安全的

进行下行转换(把基类的指针或引用转换成派生类表示),由于没有动态类型检查,是不安全的
指针转换
//father 为基类 son 为派生类
father *f = NULL;
son *s = NULL;
son *s1 = static_cast(f);//向下转换 不安全
father *f1 = static_cast(s);//向上转换,安全
//没有亲属关系不能转换
//other *o = static_cast(s);
引用转换
father f;
son s;
father &ref_f = f;
son &ref_s = s;
static_cast(ref_s);//向上
static_cast(ref_f);//向下

还可以:

把空指针转换成目标类型的空指针

把任何类型的表达式转换为void类型

但不可以:

static_cast不能转换掉expression的const、volitale或者__unaligned属性

特点:

可以实现C++中内置基本数据类型之间的相互转换

只能在有相互联系的类型中进行相互转换

动态转换(dynamic_cast) 基础类型不能使用动态转换
//char a = 'a';
//dynamic_cast(a); 基础类型不能使用动态转换
用于类层次间上行转换和下行转换
上行转换时,dynamic_cast和static_cast效果一样

下行转换时,dynamic_cast具有类型检查的功能,比static_cast安全
  father *f = NULL;
  son *s = NULL;
  father *f1 = dynamic_cast(s);
  //son *s1 = dynamic_cast(f); 向下不安全 检查 不通过编译
多态后可以向下转换(基类中要有虚函数)
class father2
{
public:
    virtual void func();
};
class son2 : public father2
{
public:
    virtual void func();
};
//发生多态时,向下转换
void test()
{
    father2 *f = new son2;
    dynamic_cast(f);
}

常量转换(const_cast)

去除常量性的对象必须为指针或引用。

常量指针/引用被转换成非常量指针/引用,并且仍然指向原来的对象

const int *p = NULL;
int *newp = const_cast(p); //const int* ->int *
int *pp = NULL;
const int *newpp = const_cast(pp); //int* ->const  int *

不能对非指针和非引用的变量使用去除其const


重新解释转换(reinterpret_cast)

使用reinterpret_cast强制转换过程仅仅只是比特位的拷贝,因此在使用过程中需要特别谨慎,不安全

改变指针或引用的类型、将指针或引用转换为一个足够长度的整形、将整型转换为指针或引用类型。

int a = 10;
int *p = reinterpret_cast(a); //整数->指针
father *f = NULL;
other *o = reinterpret_cast(f); //father->other
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779471.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号