static_castconst_cast

解决方案 »

  1.   

    static_cast是进行转型,静态绑定型别
    const_cast只改变变量的常量性,不改变型别
      

  2.   

    int a = 1;
    const int *b = &a;
    int *p = const_cast<int*>b;
      

  3.   

    那上面那个 static_cast 呢/
      

  4.   

    static_cast比较像原来c的强制转型
    当然这些转型都是建立在可能的基础上
      

  5.   

    long size;
    short i = static_cast<short>(filesize);
    这里把 long 强制转换成 short 相当于 i = (short)filesize;
    这个过程都是在编译时进行的,不做任何运行时检查,所以没有效率问题。
    但是后一种方法不考虑类型安全,即使非法转换也不会有任何警告。
    而前一种方法在转换时同时也检查转换的可行性。
      

  6.   

    const_cast 是把const变量转换成普通的变量。
      

  7.   

    static_cast、const_cast都是转换掉表达式的常量性。
      

  8.   

    MSDN:
    static_cast   Used for conversion of nonpolymorphic types.
    const_cast   Used to remove the const, volatile, and __unaligned attributes.
      

  9.   

    static_cast类似于以前C的类型转换
    const_cast用来转换const类型
      

  10.   

    msdn 原文
    The const_cast operator can be used to remove the const, volatile, and __unaligned attribute(s) from a class.A pointer to any object type or a pointer to a data member can be explicitly converted to a type that is identical except for the const, volatile, and __unaligned qualifiers. For pointers and references, the result will refer to the original object. For pointers to data members, the result will refer to the same member as the original (uncast) pointer to data member. Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.You cannot use the const_cast operator to directly override a constant variable's constant status.The const_cast operator converts a null pointer value to the null pointer value of the destination type.postfix-expression: 
    static_cast < type-id > ( expression ) 
    The static_cast operator converts expression to the type of type-id based solely on the types present in the expression. No run-time type check is made to ensure the safety of the conversion.The static_cast operator can be used for operations such as converting a pointer to a base class to a pointer to a derived class. Such conversions are not always safe.In general you use static_cast when you want to convert numeric data types such as enums to ints or ints to floats, and you are certain of the data types involved in the conversion. static_cast conversions are not as safe as dynamic_cast conversions, because static_cast does no run-time type check, while dynamic_cast does. A dynamic_cast to an ambiguous pointer will fail, while a static_cast returns as if nothing were wrong; this can be dangerous. Although dynamic_cast conversions are safer, dynamic_cast only works on pointers or references, and the run-time type check is an overhead. See dynamic_cast for more details.