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);
    }
    

      

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

  • 相关阅读:
    组合容斥计数技巧
    [BZOJ3456]城市规划:DP+NTT+多项式求逆
    [BZOJ4456][ZJOI2016]旅行者:分治+最短路
    [51nod1383&1048]整数分解为2的幂:DP
    [BZO3572][HNOI2014]世界树:虚树+倍增
    树上最小权链覆盖:可并堆
    [BZOJ4237]稻草人:CDQ分治+单调栈
    [BZOJ3453]tyvj 1858 XLkxc:拉格朗日插值
    [BZOJ5463][APIO2018]铁人两项:Tarjan+圆方树
    [BZOJ4695]最假女选手:segment tree beats!
  • 原文地址:https://www.cnblogs.com/qq209049127/p/10732417.html
Copyright © 2011-2022 走看看