c++强制类型转换(static_cast,const_cast,dynamic_cast,reinterpret_cast)
static_cast <typeid>(exdlvssion)
static_cast 很像 C 语言中的旧式类型转换。它能进行基础类型之间的转换,也能将带有可被单参调用的构造函数或用户自定义类型转换操作符的类型转换,还能在存有继承关系的类之间进行转换(即可将基类转换为子类,也可将子类转换为基类),还能将 non-const对象转换为 const对象(注意:反之则不行,那是const_cast的职责。)。
double d = 3.14159265;
int i = static_cast<int>(d); class A {};
class B
{
public:
B (A a) {};
};
A a;
B b = static_cast<B>(a); class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast<CDerived *>(a);
注意:static_cast 转换时并不进行运行时安全检查,所以是非安全的,很容易出问题。因此 C++ 引入 dynamic_cast 来处理安全转型。
dynamic_cast<typeid>(exdlvssion)
dynamic_cast 主要用来在继承体系中的安全向下转型。它能安全地将指向基类的指针转型为指向子类的指针或引用,并获知转型动作成功是否。如果转型失败会返回null(转型对象为指针时)或抛出异常(转型对象为引用时)。dynamic_cast 会动用运行时信息(RTTI)来进行类型安全检查,因此 dynamic_cast 存在一定的效率损失。(我曾见过属于优化代码80/20法则中的20那一部分的一段游戏代码,起初使用的是 dynamic_cast,后来被换成 static_cast 以提升效率,当然这仅是权宜之策,并非好的设计。)
class CBase { };
class CDerived: public CBase { };
CBase b;
CBase* pb;
CDerived d;
CDerived* pd;
pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // error: base-to-derived
上面的代码中最后一行会报如下错误 ,这是因为 dynamic_cast 只有在基类带有虚函数的情况下才允许将基类转换为子类。
class CBase
{
virtual void dummy() {}
};
class CDerived: public CBase
{
int a;
}; int main ()
{
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd1, * pd2;
pd1 = dynamic_cast<CDerived*>(pba);
pd2 = dynamic_cast<CDerived*>(pbb);
return ;
}
结果是:上面代码中的 pd1 不为 null,而 pd2 为 null。
class BaseClass {
public:
int m_iNum;
virtual void foo(){}; //基类必须有虚函数。保持多台特性才能使用dynamic_cast
};
class DerivedClass: public BaseClass {
public:
char *m_szName[];
void bar(){};
};
BaseClass* pb = new DerivedClass();
DerivedClass *pd1 = static_cast<DerivedClass *>(pb); //子类->父类,静态类型转换,正确但不推荐
DerivedClass *pd2 = dynamic_cast<DerivedClass *>(pb); //子类->父类,动态类型转换,正确
BaseClass* pb2 = new BaseClass();
DerivedClass *pd21 = static_cast<DerivedClass *>(pb2); //父类->子类,静态类型转换,危险!访问子类m_szName成员越界
DerivedClass *pd22 = dynamic_cast<DerivedClass *>(pb2); //父类->子类,动态类型转换,安全的。结果是NULL
dynamic_cast 也可在 null 指针和指向其他类型的指针之间进行转换,也可以将指向类型的指针转换为 void 指针(基于此,我们可以获取一个对象的内存起始地址 const void * rawAddress = dynamic_cast<const void *> (this);)。
const_cast<typeid>(exdivission)
前面提到 const_cast 可去除对象的常量性(const),它还可以去除对象的易变性(volatile)。const_cast 的唯一职责就在于此,若将 const_cast 用于其他转型将会报错。
void print (char * str)
{
cout << str << endl;
}
int main ()
{
const char * c = " http://www.cppblog.com/kesalin/";
print ( const_cast<char *> (c) );
return ;
}
reinterpret_cast<typeid>(exdivssion>
reinterpret_cast 用来执行低级转型,如将执行一个 int 的指针强转为 int。其转换结果与编译平台息息相关,不具有可移植性,因此在一般的代码中不常见到它。reinterpret_cast 常用的一个用途是转换函数指针类型,即可以将一种类型的函数指针转换为另一种类型的函数指针,但这种转换可能会导致不正确的结果。总之,reinterpret_cast 只用于底层代码,一般我们都用不到它,如果你的代码中使用到这种转型,务必明白自己在干什么。
int doSomething(){ return ; }
typedef void(*FuncPtr)();//FuncPtr is 一个指向函数的指针,该函数没有参数,返回值类型为 void
FuncPtr funcPtrArray[];//10个FuncPtrs指针的数组 让我们假设你希望(因为某些莫名其妙的原因)把一个指向下面函数的指针存入funcPtrArray数组:
funcPtrArray[] = &doSomething; // 编译错误!类型不匹配,reinterpret_cast可以让编译器以你的方法去看待它们:funcPtrArray
funcPtrArray[] = reinterpret_cast<FuncPtr>(&doSomething); //不同函数指针类型之间进行转换
c++强制类型转换(static_cast,const_cast,dynamic_cast,reinterpret_cast)的更多相关文章
- static_cast,const_cast,dynamic_cast,reinterpret_cast
除非必要,尽量不要对变量进行强制转换.这是因为强制转换是存在风险的,但实际上在某种情况下,转型是必需的. 旧式C转型方式为(type)expression,即由一对小括号加上一个对象名称组成,而这种语 ...
- 【C++】 四种强制类型转换(static_cast 与 dynamic_cast 的区别!)
强制类型转换 1. static_cast 2. dynamic_cast 3. const_cast 4. reinterpret_cast 5. 为什么要需要四种类型转换? 1. static_c ...
- c++中的强制转换static_cast、dynamic_cast、reinterpret_cast的不同用法儿
c++中的强制转换static_cast.dynamic_cast.reinterpret_cast的不同用法儿 虽然const_cast是用来去除变量的const限定,但是static_cast ...
- C++提供的四种新式转换--const_cast dynamic_cast reinterpret_cast static_cast
关于强制类型转换的问题,许多书都讨论过,写的最具体的是C++之父的<C++的设计和演化>. 最好的解决方法就是不要使用C风格的强制类型转换,而是使用标准C++的类型转换符:static_c ...
- static_cast、dynamic_cast reinterpret_cast
关于强制类型转换的问题,很多书都讨论过,写的最详细的是C++ 之父的<C++ 的设计和演化>.最好的解决方法就是不要使用C风格的强制类型转换,而是使用标准C++的类型转换符:static_ ...
- C++强制类型转换操作符 const_cast
const_cast也是一个强制类型转换操作符.<C++ Primer>中是这样描述它的: 1.将转换掉表达式的const性质. 2.只有使用const_cast才能将const性质性质转 ...
- c++强制类型转换:dynamic_cast、const_cast 、static_cast、reinterpret_cast
c++强制类型转换:dynamic_cast.const_cast .static_cast.reinterpret_cast 博客分类: C/C++ CC++C#编程数据结构 dynamic_ca ...
- C++强制类型转换:static_cast、dynamic_cast、const_cast、reinterpret_cast
1. c强制转换与c++强制转换 c语言强制类型转换主要用于基础的数据类型间的转换,语法为: (type-id)expression//转换格式1 type-id(expression)//转换格式2 ...
- C++里的强制类型转换符reinterpret_cast、static_cast 、dynamic_cast、const_cast 区别
C 风格(C-style)强制转型如下: (T) exdivssion // cast exdivssion to be of type T 函数风格(Function-style)强制转型使用这样的 ...
随机推荐
- SelectedValue 失效
/// <summary> /// 绑定代表下拉选项 /// </summary> public void BindOwnerDataII(string unitId, str ...
- django不要设置datetime字段auto_now=True
django model的datetime字段如果设置了auto_now=True的话,update该记录的时候即使没有更新它的时间字段,它的时间字段依然会执行一遍auto_now,时间会变成当前更新 ...
- 立体匹配:关于Middlebury提供的源码的简化使用
Middlebury提供的源码,虽然花了不到一个小时就运行起来啦.但说实话,它那循环读取脚本命令来执行算法真是让我费了不少头脑,花了近三天时间,我才弄明白了它的运行机制.你说,我就想提取一下算法,你给 ...
- (easy)LeetCode 228.Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges. For example, give ...
- hcatalog配置
https://cwiki.apache.org/confluence/display/Hive/HCatalog+CLI hive的配置中添加: export PATH=$PATH:$HIVE ...
- 常见的MIME类型
超文本标记语言文本 .htm,.html text/html 普通文本 .txt text/plain GIF图形 .gif image/gif JPEG图形 .ipeg,.jpg image/jpe ...
- Cocos2d-x 3.4版本 新建项目 IOS版
打开终端 cd进入cocos2d-x-3.0/tools/cocos2d-console/bin 然后执行下面命令 ./cocos.py new testHuoFei -p com.huofei.ap ...
- body-content取值的意义
body-content的值有下面4种: <xsd:enumeration value="tagdependent"/> <xsd:enumeration val ...
- Android开发-API指南-设备兼容性
Device Compatibility 英文原文:http://developer.android.com/guide/practices/compatibility.html 采集日期:2014- ...
- CODEVS 1001 舒适的路线
思路:先按照速度大小对边排序,再枚举最终路径中的速度最大值,并查集,更新答案 #include<iostream> #include<vector> #include<a ...