Summary of cast function in C + +

Source: Internet
Author: User

There are mainly four types of cast operators in standard C + +:

Const_cast,reinterpret_cast,static_cast,dynamic_cast and so on.

1) static_cast<t*> (a)

Converting address A to type t,t and a must be a pointer, reference, arithmetic type, or enumeration type.

Expression static_cast<t*> (a), the value of a is converted to the type T specified in the template. During run-time conversion, no type checking is performed to ensure the security of the conversion.

Example:

class B { ... };
class D : public B { ... };
void f(B* pb, D* pd)
{
D* pd2 = static_cast<D*>(pb); // 不安全, pb可能只是B的指针

B* pb2 = static_cast<B*>(pd); // 安全的
...
}
class B { ... };
class D : public B { ... };
void f(B* pb, D* pd)
{
D* pd2 = static_cast<D*>(pb); // 不安全, pb可能只是B的指针

B* pb2 = static_cast<B*>(pd); // 安全的
...
}

class B { ... };
class D : public B { ... };
void f(B* pb, D* pd)
{
D* pd2 = static_cast<D*>(pb); // 不安全, pb可能只是B的指针

B* pb2 = static_cast<B*>(pd); // 安全的
...
}

2) dynamic_cast<t*> (a)

completes the promotion in the class hierarchy. T must be a pointer, reference, or a pointer of no type. A must be an expression that determines a pointer or reference.

An expression dynamic_cast<t*> (a) converts a value to an object pointer of type T. If the type T is not a base type of a, the operation returns a null pointer.

Example:

class A { ... };
class B { ... };
void f()
{
A* pa = new A;
B* pb = new B;
void* pv = dynamic_cast<A*>(pa);
// pv 现在指向了一个类型为A的对象
...
pv = dynamic_cast<B*>(pb);
// pv 现在指向了一个类型为B的对象
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.