C++类型转换(十四)

32 篇文章 0 订阅
  1. 静态类型转换  static_cast
    1. 语法 static_cast<目标类型>(原变量/原对象)
    2. 允许父子之间的指针或者引用的转换
    3. 允许内置数据类型转换
  2. 动态类型转换  dynamic_cast
    1. 不允许内置数据类型转换
    2. 允许父子之间指针或者引用的转换
      1. 父转子  不安全的  转换失败
      2. 子转父  安全   转换成功
      3. 如果发生多态,总是安全,可以成功
    3. 语法 dynamic_cast<目标类型>(原变量/原对象)
  3. 常量转换   const_cast
    1. 只允许 指针或者引用 之间转换
    2. 语法 const   _cast<目标类型>(原变量/原对象)
  4. 重新解释转换 reinterpret_cast
    1. 最不安全一种转换,不建议使用
#include<iostream>
#include<string>
using namespace std;

class father {};
class son:public father {};
class other {};

void test01() {
	//静态类型转换
	char c1 = 'c';
	double d1 = static_cast<double>(c1);
	cout << d1 << endl;

	father *fp1=NULL;
	son *sp1=NULL;
	//子转父
	father *fp2 = static_cast<father *>(sp1);
	//父转子
	son *sp2 = static_cast<son *>(fp1);
}

void test02() {
	//动态类型转换,比静态类型转换更安全
	// 不能转,不安全
	//char c1 = 'c';
	//double d1 = dynamic_cast<double>(c1);
	//cout << d1 << endl;

	father* fp1 = NULL;
	son* sp1 = NULL;
	//子转父
	father* fp2 = dynamic_cast<father*>(sp1);
	//父转子,不能转,不安全
	//son* sp2 = dynamic_cast<son*>(fp1);
}

void test03() {
	//不可以将非指针或非引用做const_cast转换
	const int* p = NULL;
	int* pp = const_cast<int*>(p);

	const int* ppp = const_cast<const int*>(pp);

	//const int a = 10;
	//int b = const_cast<int>(a);

	int num = 10;
	int& numRef = num;

	const int& num2 = const_cast<const int&>(numRef);
}

//重新解释转换  reinterpret_cast 最不安全一种转换,不建议使用
void test04() {
	int a = 10;
	int* p = reinterpret_cast<int*>(a);

	father* fp = NULL;
	other* op = reinterpret_cast<other *>(fp);

    int* sp1 = new int;
	other* ss= reinterpret_cast<other*>(sp1);
	delete ss;
}

int main() {
	test01();
	test02();
	test03();
	test04();
	system("pause");
	return EXIT_SUCCESS;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值