zoukankan      html  css  js  c++  java
  • c++中4种与类型转换相关的关键字(P23)

    c++中4种与类型转换相关的关键字

    static_cast  

    reinterpret_cast

    dynamic_cast

    const_cast

    1.**static_cast------运算符完成相关类型之间的转换**

    使用场景:如在同一类层次结构中的一个指针类型到另一个指针类型,整型到枚举类型,或者浮点型到整型等。

    例:  

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    using namespace std;
    int main()
    {
        int m=10;
        double n=static_cast<int>(m);
        double nn=m;
        int *q=static_cast<int*>(malloc(100));
        cout<<n<<endl;
        cout<<nn<<endl;
        cout<<q<<endl;
        return 0;
    }

    2.**reinterpret_cast------处理互不相关类型之间的转换**

    使用场景:如从整型到指针,一种类型的指针到另一种类型的指针等

    例: int a=10;

       double* b=reinterpret_cast<double*>(a); //b的转换结果为0x0000000a

    3.**dynamic_cast------处理基类型到派生类型的转换**(这个说法不是很准确,为了好理解先这么写)

    使用场景:基类必须有虚函数,即为多态时,可以转换

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    using namespace std;
    class Base
    {
        virtual int test(){return 0;}
    };
    class Derived:public Base
    {
    public:
        virtual int test(){return 1;}
    };
    int main()
    {
        Base cbase;
        Derived cderived;
        Base *p1=new Base;
        Base *p2=new Derived;  //可以为父类指针new子类对象,而不能为子类指针new父类对象,因为子类包含有父类,把子指针赋给父指针时其实只是把子类中父类部分的地址赋给了父类指针而已,而父类里没有包含子类,所以不能复制
    
    //Derived* pD1=dynamic_cast<Derived*>(p1);//p1没有真正指向派生类,判断抛出异常
    //cout<<pD1->test()<<endl;
    Derived* pD2=dynamic_cast<Derived*>(p2);
    cout<<pD2->test()<<endl;   //输出1
    //Derived& pd1=dynamic_cast<Derived&> (*p1); //p1没有真正指向派生类,判断抛出异常
    Derived& pd2=dynamic_cast<Derived&>(*p2);
    cout<<pd2.test()<<endl;   //输出1
    }

    4,const_cast用来移除变量的const或volatile限定符。

    一句话:强制去掉const(或volatile)  必须使用const_cast 。

    注:
    volatile的作用是: 作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值.
    简单地说就是防止编译器对代码进行优化.比如如下代码:
    a=1;
    a=2;
    a=3;
    a=4;
    对外部硬件而言,上述四条语句分别表示不同的操作,会产生四种不同的动作,但是编译器却会对上述四条语句进行优化,认为只有a=4(即忽略前三条语句,只产生一条机器代码)。如果键入volatile,则编译器会逐一的进行编译并产生相应的机器代码(产生四条代码).
  • 相关阅读:
    什么是模板方法模式?
    在多线程环境下,SimpleDateFormat 是线程安全的吗?
    抽象类是什么?它与接口有什么区别?你为什么要使用过 抽象类?
    依赖注入和工程模式之间有什么不同?
    什么时候使用访问者模式?
    Java 中,受检查异常 和 不受检查异常的区别?
    说出 5 个 JDK 1.8 引入的新特性?
    什么是领域驱动设计?
    列举 IoC 的一些好处?
    什么是 Spring 配置文件?
  • 原文地址:https://www.cnblogs.com/dshn/p/8341498.html
Copyright © 2011-2022 走看看