八、C++ 类型强转

2023年5月6日08:09:13

八、C++ 类型强转

1.静态类型转换

1.语法格式

static_cast<目标类型> (标识符)

2.转化规则
在一个方向上可以作隐式转换,在另外一个方向上就可以作静态转换。

int a = 10;
int b = 3;
cout<<static_cast<float>(a)/b<<endl; //float = int int = float
return 0;
int *p; void *q;
p = static_cast<int*>(q);
char *p = static_cast<char*>(malloc(100));

2.重解释类型转换

1.语法格式

reinterpret_cast<目标类型> (标识符)

2.转化规则
将数据以二进制存在形式的重新解释,在双方向上都不可以隐式类型转换的,则需要重解释类型转换

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
	int x = 0x12345648;
	char *p = reinterpret_cast<char*>(&x);
	//char*p = static_cast<char*>(&x); error
	printf("%x\n",*p);
	int a[5] = {1,2,3,4,5};
	int *q = reinterpret_cast<int*>(a+1);
	printf("%x\n",*q);
	return 0;
}

八、C++ 类型强转

3.常类型转换

1.语法格式

const_cast<目标类型> (标识符) //目标类类型只能是指针或引用。

2.语法规则
用来移除对象的常量性使用 const_cast 去除 const 限定的,目的不是为了修改它的内容,使用 const_cast 去除 const 限定,通常是为了函数能够接受这个实际参数。

#include <iostream>
using namespace std;
void func(int & ref) //别人己经写好的程序或类库
{
	cout<<ref<<endl;
}
int main(void)
{
	const int m = 1;
	func(const_cast<int&>(m));
	return 0;
}

脱掉const后的引用或指针可以改吗

#include <iostream>
using namespace std;
int main()
{
	const int x = 200;
	int & a =const_cast<int&>(x); // int &a = x;
	a = 300;
	cout<<a<<x<<endl;
	cout<<&a<<"---"<<&x<<endl;
	int *p =const_cast<int*>(&x); // int *p = &x;
	*p = 400;
	cout<<a<<*p<<endl;
	cout<<p<<"---"<<&x<<endl;
	struct A
	{
		int data;
	};
	const A xx = {1111};
	A &a1 = const_cast< A&>(xx);
	a1.data = 222;
	cout<<a1.data<<xx.data<<endl;
	A *p1 = const_cast<A*>(&xx);
	p1->data = 333;
	cout<<p1->data<<xx.data<<endl;
	return 0;
}

八、C++ 类型强转
结论:可以改变 const 自定义类的成员变量,但是对于内置数据类型,却表现未定义行为
3.const 常变量(补充)
C++中 const 定义的变量称为常变量。变量的形式,常量的作用,用作常量,常用于取代#define 宏常量

4.动态类型转换

1.语法格式

dynamic_cast<目标类型> (标识符)

用于多态中的父子类之间的强制转化

  • 作者:ALL IN C
  • 原文链接:https://blog.csdn.net/qq_43414070/article/details/121021741
    更新时间:2023年5月6日08:09:13 ,共 1454 字。