用C++的静态和动态cast 替代C语言风格的老式的强制类型转换

http://studiofreya.com/c/cpp-casts/

C++ casts

Casting is simply converting one type of data into an other type of data.

The old type C-style cast is allowed in C++, but I would highly discourage it.

1
2
3
// DO NOT USE
int low = 1500;
short lower = ( short ) low;

Use the static_cast construct instead. It’s more safe and it does some type checking and it always does the same. The (short) cast could possibly do harmfull stuff to your program and computer when used wrong.

1
2
3
// use instead of (short)
int low = 1500;
short lower = static_cast < short >( low );

The next type of cast is dynamic_cast. It’s function is to downcast and upcast to/from a base type to a type further down/up in the hierarchy.

1
2
3
4
5
6
7
8
9
10
11
class A;
class B : public A;
 
// B inherits A
B *b = new B();
 
// Cast up to A
A *a = dynamic_cast <A*>( b );
 
// Cast down from A to B
B *bcast = dynamic_cast <B*>( a );

With the next to casts we’re getting our hands dirty. Reinterpret_cast takes some data and pretends it’s something else. Const_cast removes the const modifier to a variable and is also troublesome. If you are in the need for const_cast, I’d say you have something wrong with the design of your application.

In my experience, reinterpret_cast is good for casting from and to void*.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值