c++的四种转型关键字

来源:互联网 发布:wordpress适合优化吗 编辑:程序博客网 时间:2024/06/06 17:54

const_cast

Syntax:

    TYPE const_cast<TYPE> (object);

The const_cast keyword can be used to remove the const or volatile property from an object. The target data type must be the same as the source type, except (of course) that the target type doesn't have to have the same const qualifier. The type TYPE must be a pointer or reference type.

For example, the following code uses const_cast to remove the const qualifier from a object:

class Foo {
public:
void func() {} // a non-const member function
};
 
void someFunction( const Foo& f ) {
f.func(); // compile error: cannot call a non-const
// function on a const reference

Foo &fRef = const_cast<Foo&>(f);
fRef.func(); // okay
}



dynamic_cast

Syntax:

    TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);

The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.

If you attempt to cast to a pointer type, and that type is not an actual type of the argument object, then the result of the cast will be NULL.

If you attempt to cast to a reference type, and that type is not an actual type of the argument object, then the cast will throw a std::bad_cast exception.

  struct A {
virtual void f() { }
};
struct B : public A { };
struct C { };
 
void f () {
A a;
B b;
 
A* ap = &b;
B* b1 = dynamic_cast<B*> (&a); // NULL, because 'a' is not a 'B'
B* b2 = dynamic_cast<B*> (ap); // 'b'
C* c = dynamic_cast<C*> (ap); // NULL.
 
A& ar = dynamic_cast<A&> (*ap); // Ok.
B& br = dynamic_cast<B&> (*ap); // Ok.
C& cr = dynamic_cast<C&> (*ap); // std::bad_cast
}



reinterpret_cast

Syntax:

    TYPE reinterpret_cast<TYPE> (object);

The reinterpret_cast operator changes one data type into another. It should beused to cast between incompatible pointer types.

 

 

static_cast

Syntax:

    TYPE static_cast<TYPE> (object);

The static_cast keyword can be used for any normal conversion between types. This includes any casts between numeric types, casts of pointers and references up the hierarchy, conversions with unary constructor, conversions with conversion operator.For conversions between numeric types no runtime checks if data fits the new type is performed.Conversion with unary constructor would be performed even if it is declared as explicit

It can also cast pointers or references down and across the hierarchy as long as such conversion is available and unambiguous. No runtime checks are performed.

 

 

原创粉丝点击