zoukankan      html  css  js  c++  java
  • Type Casting in C++

    Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:

    Implicit conversion
    Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

    Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

    Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions.

    Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.

    Explicit conversion
    C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

    The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors.

    代码
    #include <iostream>
    using namespace std;

    class A {

    public:
        A()
        {
            age
    =30;
        }
       
    int age;
    };
    class B {
    public:
       
    int Age;
        B (A a) {Age
    =a.age*100;
        }
    };

    void CastingSample()
    {
       
    //implicit converstion for fundamental data type
        short a=2000;
       
    int b;
        b
    =a;
       
    // impliclit converstion for object, which affect classes that include specific constructors or operator functions to perform conversions
        A aa;
        B bb
    =aa;
        cout
    <<bb.Age<<endl; // Output: 3000

       
    //explicit conversion
        {
           
    short a=2000;
           
    int b;
            b
    = (int) a;    // c-like cast notation
            b = int (a);    // functional notation
        }

    }

    dynamic_cast

    dynamic_cast can be used only with pointers and references to objects. dynamic_cast can do run time check to make sure the type safety. the type of converted object should be a polymorphic class. A class that declares or inherits a virtual function is called a polymorphic class.

    dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.

    static_cast
    static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. static_cast can only do compiling time check to make sure compiling type safety. static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types; Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

    reinterpret_cast
    reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

    const_cast
    This type of casting manipulates the constness of an object, either to be set or to be removed.

    typeid
    typeid allows to check the type of an expression: typeid (expression)

    This operator returns a reference to a constant object of type type_info that is defined in the standard header file <typeinfo>. This returned value can be compared with another one using operators == and != or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member.

    Notice how the type that typeid considers for pointers is the pointer type itself (both a and b are of type class CBase *). However, when typeid is applied to objects (like *a and *b) typeid yields their dynamic type (i.e. the type of their most derived complete object). If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception.

  • 相关阅读:
    26 转义符 re模块 方法 random模块 collection模块的Counter方法
    25 正则表达式
    24 from 模块 import 名字
    24 from 模块 import 名字
    24 from 模块 import 名字
    23 析构方法 items系列 hash方法 eq方法
    21 isinstance issubclass 反射 _str_ _new_ _len_ _call_
    20 属性, 类方法, 静态方法. python2与python3的区别.
    python(1)
    python之字符串格式化
  • 原文地址:https://www.cnblogs.com/whyandinside/p/1650008.html
Copyright © 2011-2022 走看看