STL:类型转换基本语法

在这里插入图片描述

一.static_cast实现

static_cast:用于一般数据类型(int,float,char,string,double)、具有继承关系的指针或引用。

//static_cast
void test01() {
	int a = 65;//A的ASCII值是65
	char c = static_cast<char>(a);
	cout << c << endl;
}

结果:
在这里插入图片描述
在这里插入图片描述

二.dynamic_cast实现

转换具有继承关系的指针或引用,在转换前会进行对象类型检查,只能由子类转父类。
由父类指针转子类会出错,类型不安全(有小到大)
由子类指针转父类指针不会出错,类型安全(由大到小)

注意:static_cast也可以转换具有继承关系的指针和引用,并且可以由父类转换为子类。
在这里插入图片描述
在这里插入图片描述

三.const_cast实现

const_cast 指针、引用或对象指针;
const_cast作用:用一个新变量增加或去除原来变量的const性;

//const_cast 指针、引用或对象指针
void test03() {
	//基础数据类型
	int a = 10;
	const int& b = a;
	//b = 1;
	int& c = const_cast<int&>(b);
	c = 20;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	cout << "c=" << c << endl;
	//指针  用一个新变量增加或去除原来变量的const性
	const int* p1 = nullptr;
	int* p2 = const_cast<int*>(p1);

	int* p3 = nullptr;
	const int* p4 = const_cast<const int*>(p3);
}

在这里插入图片描述

四.reinterpret_cast实现

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

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

//reinterpret_cast 强制类型转化
typedef void(*func1)(int, int);//函数指针
typedef int(*func2)(int, char*);
void test04() {
	//1.无关的指针类型都可以进行转换
	Building* building = nullptr;
	Animal* ani = reinterpret_cast<Animal*>(building);
	//2.函数指针的转换
	func1 f1;
	func2 f2 = reinterpret_cast<func2>(f1);
}

五.原则

  1. 程序员必须清楚的知道要转变的变量,转换前是什么类型,转换后是什么类型,以及转换后什么后果。
  2. 一般情况下,不建议类型转换,避免进行类型转换。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]提供了关于强制类型转换的示例代码,其中使用了reinterpret_cast来进行指针类型转换。这种转换可以将无关的指针类型进行转换,包括函数指针。引用\[2\]介绍了const_cast的用法,它可以用来增加或去除变量的const性质。在示例代码中,const_cast被用来去除const限定符,从而修改了原来的变量。引用\[3\]提供了关于西门子PLC STL中的一些状态位的解释,包括首位检测位、逻辑操作结果位、状态位、溢出位等等。这些状态位在编程中可以用来判断程序的执行结果或进行错误检查。 关于西门子PLC STL的具体内容,由于没有提供更多的引用内容,我无法给出更详细的回答。如果您有具体的问题或需要了解特定的内容,请提供更多的信息,我将尽力为您提供帮助。 #### 引用[.reference_title] - *1* *2* [STL类型转换基本语法](https://blog.csdn.net/weixin_44190648/article/details/122318140)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [西门子PLC中STL语言状态字](https://blog.csdn.net/qq_18671205/article/details/105382879)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值