官术网_书友最值得收藏!

Type conversions

A type conversion occurs whenever a value is assigned to a compatible variable, which is not the exact same type as the value. Whenever a rule for conversion exists, this conversion can be done implicitly, otherwise an explicit hint (cast) can be provided to the compiler to invoke a specific rule where ambiguity exists.

Whereas C only has implicit and explicit type casting, C++ expands on this with a number of template-based functions, allowing you to cast both regular types and objects (classes) in a variety of ways:

  • dynamic_cast <new_type> (expression)
  • reinterpret_cast <new_type> (expression)
  • static_cast <new_type> (expression)
  • const_cast <new_type> (expression)

Here, dynamic_cast guarantees that the resulting object is valid, relying on runtime type information (RTTI) (see the later section on it) for this. A static_cast is similar, but does not validate the resulting object.

Next, reinterpret_cast can cast anything to anything, even unrelated classes. Whether this conversion makes sense is left to the developer, much like with a regular explicit conversion.

Finally, a const_cast is interesting in that it either sets or removes the const status of a value, which can be useful when you need a non-const version of a value for just one function. This does, however, also circumvent the type safety system and should be used very cautiously.

主站蜘蛛池模板: 巴林左旗| 枣强县| 民权县| 于田县| 晋州市| 砀山县| 普陀区| 青神县| 沙坪坝区| 长子县| 铜川市| 临桂县| 原阳县| 忻州市| 富川| 翁源县| 曲沃县| 呼玛县| 和龙市| 洛浦县| 丰镇市| 肇州县| 沭阳县| 舞钢市| 贡嘎县| 慈溪市| 鹿邑县| 宁远县| 苍梧县| 广南县| 丰原市| 通化市| 镇巴县| 大厂| 马关县| 丹巴县| 梓潼县| 嘉禾县| 商洛市| 镇坪县| 漯河市|