[C ++ base] and four types of conversion implicit type conversion

static_cast<type-id >( expression )  

For switching between numeric types, it can also be used to convert between the pointer determined at compile time, high efficiency, but must guarantee their own safety.

(1) for conversion between the values ​​can be switched between the relevant pointer void *

   


(2) switch between base and derived classes (there must be a relationship between two classes inherited)


Upconverter: subclass pointer or reference into a base class represents - Safety

Downstream converter: base pointer or reference into a subclass represents - risk (no dynamic type checking)


   

dynamic_cast < type-id> ( expression)

Only for switching between a reference object and a pointer is required virtual functions. Especially downcast, it is safe. Static_cast with different downlink conversion, the conversion of dynamic_cast checks whether a valid full return the requested object, otherwise it returns a value of NULL. 

Detection at runtime, is RTTI data information, run-time detection, security, but inefficient based.

  

How to convert dynamic_cast to ensure it is safe?

The introduction of RTTI, inheritance chain name related information that may be stored like running record of class and class. So that the object can know his name and position in the inheritance chain. Because RTTI relies on the virtual table, so use dynamic_cast must have a corresponding class virtual function.


const_cast< type-id> ( expression)

This conversion type object passed const attribute manipulation, or removal or setting:
Code:
class C {};
const new new C C * A =;
C = B * const_cast <C *> (A);

reinterpret_cast< type-id> ( expression)

For use in any type of conversion between a pointer (or reference); and a conversion between the pointer and a sufficiently large integer type; an integer type (including enumerated types) to the pointer type, ignoring size.


Implicit type conversion


(1)两种常用的实现隐式类类型转换的方式:
a、使用单参数的构造函数或N个参数中有N-1个是默认参数的构造函数

b、使用operator目标类型() const

 

例如:
class Rational {
public:
  ...
  operator double()const;                  // 转换Rational类成double类型
};
在下面这种情况下,这个函数会被自动调用:
Rational r(1,2);                           // r 的值是1/2 
double d = 0.5 *r;                         // 转换 r 到double,然后做乘法

 

(2) 避免隐式类型转换:单参数的构造函数或N个参数中有N-1个是默认参数的构造函数声明之前加上explicit

 

Guess you like

Origin blog.csdn.net/qq_35886593/article/details/90691614