zoukankan      html  css  js  c++  java
  • c++中的类型转换

    c++提供四种类型转换

    static_cast转换内置数据类型和具有继承关系的指针和引用

    
    

    class Building{};
    class Animal{};
    class Cat :public Animal{};

    void test01()
    {
    	int a = 97;
    	char c = static_cast<char>(a);
    	cout << c << endl;
    	//父类指针转换为子类指针
    	Animal *ani = NULL;
    	Cat *cat = static_cast<Cat*>(ani);
    	//子类指针转换为父类指针
    	Cat *soncat = NULL;
    	Animal *anifather = static_cast<Animal*>(soncat);
    	//引用
    	Animal aniobj;
    	Animal &aniref = aniobj;
    	Cat&cat = static_cast<Cat&>(aniref);
    
    	Cat catobj;
    	Cat&catref = catobj;
    	Animal &anifather2 = static_cast<Animal&>(catref);
    }

     

    dynamic_cast转换具有继承关系的指针或引用,在转换之前进行对象类型检查
      子类指针可以装换为父类指针(从小到大),类型安全
      父类指针转换为子类指针(从小到大),不安全

    void test02()
    {
    	Animal*ani = NULL;
    	Cat*cat = dynamic_cast<Cat*>(ani);//报错原因在于dynamic_cast做类型安全检查
    
    	Cat*cat = NULL;
    	Animal *ani = dynamic_cast<Animal*>(cat);
    }
    结论:dynamic只能转换具有继承关系的指针或者引用,并且只能由子类型转换成基类型

     const_cast  指针 引用或者对象指针

    增加或者去除变量的const性
    void test03()
    {
    	//1.基础数据类型
    	int a = 10;
    	const int &b = a;
    	int &c = const_cast<int&>(b);
    	c = 20;
    	//2.指针
    	const int*p = NULL;
    	int *p2 = const_cast<int*>(p);
    
    	int *p3 = NULL;
    	const int *p4 = const_cast<const int *>(p3);
    	
    }
    

      

    reinterpret_cast强制类型转换 无关的指针类型 包括函数指针都可以

    typedef void(*FUNC1)(int, int);
    typedef int(*FUNC2)(int, char*);
    void test04()
    {
    	//1.无关的指针类型都可以进行转换
    	Building*building = NULL;
    	Animal* ani = reinterpret_cast<Animal*>(building);
    
    	//2.函数指针转换
    	FUNC1 func1;
    	FUNC2 fun2 = reinterpret_cast<FUNC2>(func1);
    }
    

      

    提示:必须清楚的知道要转变的变量,转换前是什么类型,转换后是什么类型
    一般情况下,不建议类型转换,避免进行类型转换

  • 相关阅读:
    Pytorch手写线性回归
    numpy+sklearn 手动实现逻辑回归【Python】
    如何用TensorFlow实现线性回归
    进程、线程和携程的通俗解释【刘新宇Python】
    即时通信WebSocket 和Socket.IO
    gRPC【RPC自定义http2.0协议传输】
    Django中MySQL事务的使用
    模拟电磁曲射炮_H题 方案分析【2019年电赛】【刘新宇qq522414928】
    Gitflow工作流
    雪花算法【分布式ID问题】【刘新宇】
  • 原文地址:https://www.cnblogs.com/qq209049127/p/10732417.html
Copyright © 2011-2022 走看看