C++中类型转换的解释

来源:互联网 发布:记忆曲线软件 编辑:程序博客网 时间:2024/06/07 04:45

这几天有场笔试,其中碰到一道题目,让我列举C++中的四种cast的转换分别是什么,有何作用,并举例说明,我虽然早知道C++有四种cast转换,但平常使用非常少也就没注意,所以那题我是没做出来,回来后打算对C++的这些类型转换方法进行小结,我做了许多实验,于是有此文,希望对你有些帮助。

 

下文中的“常规类型”指的是int、double、float、bool……这些非结构化类型,也就是不包括struct和class类型。“旧式转换”指的是C语言风格的“(NewType)(Val)”方式的转换。

 

1、static_cast不能将指针转换成非指针,也不能将非指针转换成指针。旧式强制转换一样不可以。另外我也没发现其它转换方式能将指针转换成非指针,总之指针是不能转换成非指针的

出现:error C2440: 'static_cast' : cannot convert from 'double *' to 'double'

 

2、static_cast不能将常规类型变量指针转换成另一种指针,无论是(int *)转变成(double *)或者反过来。而旧式强制转换可以。

出现:error C2440: 'static_cast' : cannot convert from 'double *' to 'int *'

 

3、static_cast可以将基类指针转换成派生类指针,反之也可以,但无法转换不相关类的指针。而旧式强制转换可以任意指针转换。

error C2440: 'static_cast' : cannot convert from 'class A *' to 'class C *'

 

4、static_cast可以将派生类转为基类,反之不可以,其余常规变量转换是允许的。这里,旧式强制转换和它一致。

error C2440: 'type cast' : cannot convert from 'class A' to 'class B'

 

5、dynamic_cast可将子类的指针/引用转换成基类的指针/引用,反之不行。其它类型的转换,dynamic_cast貌似都不能实现。这里dynamic_cast可认为是安全的转换。

error C2683: dynamic_cast : 'A' is not a polymorphic type

 

6、const_cast可以去除一个常量的const属性。

疑惑:去除const属性后可以对常量进行修改,通过调试器发现内存中的值是被改变的,可是再传递这个常量的时候,值却一直保持原状,C++如此,C却是正常的,实在古怪,我在Windows下用VC、尝试如此,在Linux下用gcc和g++尝试也如此,我原先以为和编译器的优化选项有关系,把所有优化选项关闭,照样没用,为什么?如果你知道,一定要告诉我。

 

7、reinterpret_cast能实现任意指针之间的转换,它还能将常规类型值转换成任何类型指针,可谓功能强大,但这样很明显是没有安全性可言的。按照MSDN上的说法,除非出自于某种特殊原因,一定需要这种底层的转换,否则还是用其它转换运算符来取代它好。

 

最后附带MSDN上关于四种cast的说明:

 

reinterpret_cast Operator

The reinterpret_cast operator allows any pointer to be converted into any other pointer type. It also allows any integral type to be converted into any pointer type and vice versa. Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired conversion is inherently low-level, you should use one of the other cast operators.

 

dynamic_cast Operator

The expression dynamic_cast<type-id>( expression ) converts the operand expression to an object of type type-id. The type-id must be a pointer or a reference to a previously defined class type or apointer to void. The type of expression must be a pointer if type-id is a pointer, or an l-value if type-id is a reference.

 

static_cast Operator

The expression static_cast < type-id > ( expression ) converts expression to the type of type-id based solely on the types present in the expression. No run-time type check is made to ensure the safety of the conversion.

 

const_cast operator

The const_cast operator can be used to remove the const, volatile, and __unaligned attribute(s) from a class.

 

0 0
原创粉丝点击