c++类型转换

1 四种方法概括

方法使用场景
static_cast一般的转换
dynamic_cast通常在积累和派生类之间的转换中使用
const_cast主要针对const的转换
reinterpret_cast用于没有任何关联对象之间的转换,慎用!

2 static_cast的用法

适用范围:内置数据类型以及具有继承关系的指针或者引用

#include <iostream>

class People {};
class Animal {};
class Cat: public Animal {};
  
void test01()
{
  //1.基础数据转换
  int a = 97;
  char b = static_cast<char>(a);
  std::cout << b << '\n';
  
  //2.具有继承关系的指针或者引用
  
  //错误:没有继承关系
  //People* people = nullptr;
  //Animal* ani = static_cast<People*>(people);
  
  Animal* ani = nullptr;
  Cat* cat = static_cast<Cat*>(ani);
  
  Cat* cat = nullptr;
  Animal* ani = static_cast<Animal*>(cat);
  
  Animal obj_ani;
  Animal& ani_ref = obj_ani;
  Cat& cat_ref = static_cast<Cat&>(ani_ref);
  
  Cat obj_cat;
  Cat& cat_ref = obj_cat;
  Animal& cani_ref = static_cast<Animal&>(obj_cat);  
}

int main()
{
  test01();
}

3 dynamic_cast的用法

使用范围:转换具有继承关系的指针或引用,转换前会进行对象的数据类型检查
注意:只能将子类指针转成父类指针(从大到小),不能将父类指针转成子类指针

#include <iostream>

class People {};
class Animal {};
class Cat: public Animal {};
  
void test02()
{
  
  // 错误代码
  // Animal* ani = nullptr;
  // Cat* cat = dynamic_cast<Cat*>(ani);
  
  
  Cat* cat = nullptr;
  Animal* ani = dynamic_cast<Animal*>(cat);
  
  Cat obj_cat;
  Cat& cat_ref = obj_cat;
  Animal& ani_ref = dynamic_cast<Animal&>(cat_ref);
  
}

int main()
{
  test02();
}

4 const_cast的用法

适用范围:去除或者增加对象的const属性,可以为指针,引用和对象指针

#include <iostream>
void test03()
{
  
  int a = 10;
  const int& b = a;
  int& c = const_cast<int&>(b);
  c = 20;
  std::cout << "a = " << a << std::endl; // 20
  std::cout << "b = " << b << std::endl; // 20
  std::cout << "c = " << c << std::endl; // 20
  
  const int* p = nullptr;
  int* p1 = const_cast<int*>(p);
  
  int* p2 = nullptr;
  const int* p3 = const_cast<const int*>(p2);
  
}

int main()
{
  test03();
}

5 reinterpret_cast的用法

适用范围:强制类型转换,无关的指针类型或者函数指针都可以转换

#include <iostream>

class People {};
class Animal {};

typedef void(fun1)(int, int);
typedef int(fun2)(int, char*);


void test04()
{
  //1.无关的指针类型可以转换
  People* people = nullptr;
  Animal* ani = reinterpret_cast<Animal*>(people);
  
  //2.函数指针转换
  fun1* f1;
  fun2* f2 = reinterpret_cast<fun2*>(f1);
  
  
}

int main()
{
  test04();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值