zoukankan      html  css  js  c++  java
  • C++中命名强制类型转换

    在C++中有四种命名强制类型转换:const_cast、static_cast、dynamic_cast和reinterpret_cast。这篇文章对C++中的强制类型转换讲得比较清楚。

    1. const_cast

        const_cast用于将const类型转换为非const类型,例如:

    const char *str = "hello";
    char *p = const_cast<char *>(str);

    2. static_cast和dynamic_cast

        这两种cast功能相似,但是static_cast没有动态检查的功能,而dynamic_cast有动态检查的功能。

    3. reinterpreter_cast

        例子:

    int a;
    char *c = reinterpret_cast<char *>(a);

    4. 一个小例子的分析

    class A{
        int a;
    public:
        A(){
            a = 0;
        }
    };
    class AA:public A{
        int aa;
    public:
        AA(){
            aa = 0;
        }
        virtual int get_aa(){ //如果没有这个虚函数,那么下面的dynamic_cast无法编译通过
            return aa;
        }
    };
    class B{
        int b;
    public:
        B(){
            b = 0;
        }
    };
    int main(){
        A *x;
        AA *y;
        B *z;
        static_cast<A *>(y);  //向上转换
        //static_cast<B *>(y); //无法编译通过
        dynamic_cast<B *>(y); //运行时转换的结果是NULL
        reinterpret_cast<B *>(x); //reinterpret_cast比较粗暴
        return 0;
    }

     设计得当的话,强制类型转换是可以避免的。应当尽量不要使用强制类型转换。

  • 相关阅读:
    BZOJ 2006 [NOI2010]超级钢琴
    标准打印一棵树
    COJ 0288 路径(2015升级版)
    批判树套树。。。。。。。。
    BestCoder Round #49
    蓝牙通信中读取固定长度数组的解决
    5月5日的规划
    必须要改变这样的生活
    五一结束
    五一来临
  • 原文地址:https://www.cnblogs.com/richardustc/p/2880594.html
Copyright © 2011-2022 走看看