C++ Style Casts

引入:

C++ 有四种转型风格。
static_cast, dynamic_cast, const_cast, reinterpret_cast.
下面分别介绍日常用法。

1. static_cast

最常用的是 static_cast ,常用于 int 强转 double 型.

double b = (double)10 / 2; // C 风格。
double b = static_cast<double> (10) /20; // C++ 风格

C++风格比C风格多了个前缀,改成这样的好处是 只要全局搜索关键字“static_cast” 你就能立刻找到这句代码位置了。而 c 语言风格,搜关键字“double” 的话,就不好找了,太多了。

2. const_cast

const int c = 3;
int *b = static_cast<int*>( &c ) ;  // 这是错误的转换会报错如下:
// error C2440: 'static_cast': cannot convert from 'const int *' to 'int *

改为const_cast

const int c = 3;
int* b = const_cast<int*>( &c ) ; 

static_cast 的面子不够大啊,没法把固执的const转过来,只能让 const_cast 出马。

3. dynamic_cast

前两种可以向上转型,但是向下转型就不好使。
dynamic_cast 主要用在 C++ 中类之间的向下转型。
将 指向子类对象的父类指针 向下转型为 子类指针。

class animal { public:virtual ~animal() {} };
class dog :public animal {};
class cat :public animal {};
int test_dynamic_cast()
{
    animal* a = new cat; //cat 向上转型 b 是父类指针 指向子类对象
    dog* d = dynamic_cast<dog*> (a);//父类指针 向下转型,错误
    (d != nullptr) ? std::cout << "success" << std::endl : std::cout << "cast failed" << std::endl;
    cat* c = dynamic_cast<cat*> (a);//父类指针 向下转型,正确
    (c != nullptr) ? std::cout << "success" << std::endl : std::cout << "cast failed" << std::endl;
    return 0;
}

向下转型
cat 先向上转为父类指针,然后父类向下转为 dog 是不行的,转型为 cat 是可以的。
向下转型

4. reinterpret_cast

最自由的转换,简直是位面之子,当然,结果不保证对,一般会奔溃,所以一般没人会用这个。。。

int a = 2;
double* d= reinterpret_cast<double*> (a);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值