c++中的类型转换

一 隐式转换

说明: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
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值