一 隐式转换:
说明:cpp在计算表达式之前将表达式的操作数转换为统一类型
1. bit数小于int的都转换为int,如果int不够会转换为unsigned int(32位系统short都是16bit的,int32bit,所以此情况不发生);
2. int向long转换同上,如果long不够宽,转换成unsigned long;
3. unsigned int和int一起都会被转为unsigned int(不安全,有错误),unsigned long和long之间也转为unsigned long(不安全);
4. 其他转换如数组类型转换为指针,非const转为const等。
二 显示转换:
用法:xxx_cast<des>(obj);
说明:把obj转换成des类型。
1. reinterpret_cast
说明:骗过编译器,强制把obj类型当作des类型使用(不推荐用)
2. const_cast
说明:给obj添加/去除const特性(如果使用了说明你的设计有缺陷)
3. static_cast
说明:如果A->B发生了隐式转换,那么就可以用static_cast<A>(B)把B转换成A,例如:
int a;
void *pv = &a;//发生了隐式转换
int *pn = static_cast<int*>(pv);//再转回来
4. dynamic_cast
说明:判断obj运行时是不是des类型(由于多态特性,Base指针运行时不一定指向的是Base对象),此时obj中应该有virtual函数,否则转换不成功。
/* base class */
class Base
{
virtual void foo();
};
/* derived class */
class Derived : public Base
{};
/* other class */
class Other
{};
//----------------------------------
Base *pdobj = new Derived;
Base *pb = dynamic_cast<Base*>(pdobj);// ok, pdojb assigned to pb
Other *poobj = new Other;
pb = dynamic_cast<Base*>(poobj);// pb == 0
Derived &rdobj = *(new Derived);
Other &roobj = dynamic_cast<Base&>(dobj);// throw bad_cast, not return 0, roobj must be binded to an object
typeid(obj)也经常用于对象的运行时类型,用法如下:
Base *pb;
Derived *pd;
/* 注意typeid的参数是对象,不是指针
* 如果是指针,typeif返回指针的静态
* 类型,操作对象才是正确的
*/
if (typeid(*pd) == typeid(*pb)) {
// right
}
if (typeid(*pd) == typeid(Base)) {
// right
}
if (typeid(pd) == typeid(Base)) {
// never execute
}