C++ like vs C like casts?

Possible Duplicate:
Regular cast vs. static_cast vs. dynamic_cast

i've been using C-like casts since i've been programming:

class* initializedClassInstance;
void* test = (void*) initializedClassInstance;

and i've been told somewhere that i should get used to C++ casts (static_cast, dynamic_cast...).

Is there a reason to prefer one over the other (C++ over C style)? There is a difference between static cast and dynamic cast, right? But what is it?

Thanks!


C-style casts are unsafe.

C++-style casts behave in another way. static_cast will give you a compilation error if it can't make the cast. dynamic_cast on fail will cast to NULL if you are casting pointers, and throw an exception otherwise.

So this allows you to write a safer code.


Yes, there is. It give you checks. static_cast gives you compile time checks and dynamic_cast gives you runtime checks for example.

You can read more about casts here

链接地址: http://www.djcxy.com/p/28444.html

上一篇: malloc是否懒惰地为Linux(和其他平台)上的分配创建后备页?

下一篇: 像C vs C类似的强制转换?