用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 ( b );
 
// Cast down from A to B
B *bcast = dynamic_cast ( 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*.


你可能感兴趣的:(学习学习)