栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++类型转换(十四)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++类型转换(十四)

  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
#include
using namespace std;

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

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

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

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

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

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

	const int* ppp = const_cast(pp);

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

	int num = 10;
	int& numRef = num;

	const int& num2 = const_cast(numRef);
}

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

	father* fp = NULL;
	other* op = reinterpret_cast(fp);
}

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

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/691547.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号