本篇文章是对C++ 类型转换的详细介绍,需要的朋友参考下,小编觉得这篇文章写的不错,希望能够给你带来帮助
本篇文章是对C++ 类型转换的详细介绍,需要的朋友参考下,小编觉得这篇文章写的不错,希望能够给你带来帮助
本篇文章是对C++ 类型转换的详细介绍,需要的朋友参考下,小编觉得这篇文章写的不错,希望能够给你带来帮助
|
1
|
static_cast<目标类型> (标识符) |
在一个方向上可以作隐式转换,在另外一个方向上就可以作静态转换。
|
1
2
3
4
|
int a = 10;int b = 3;cout<<static_cast<float>(a)/b<<endl; //float = int int = floatreturn 0; |
|
1
2
|
int *p; void *q;p = static_cast<int*>(q); |
|
1
|
char *p = static_cast<char*>(malloc(100)); |
|
1
|
reinterpret_cast<目标类型> (标识符) |
将数据以二进制存在形式的重新解释,在双方向上都不可以隐式类型转换的,则需要重解释类型转换
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#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;} |

|
1
|
const_cast<目标类型> (标识符) //目标类类型只能是指针或引用。 |
用来移除对象的常量性使用 const_cast 去除 const 限定的,目的不是为了修改它的内容,使用 const_cast 去除 const 限定,通常是为了函数能够接受这个实际参数。
|
1
2
3
4
5
6
7
8
9
10
11
12
|
#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后的引用或指针可以改吗
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#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;} |

结论:可以改变 const 自定义类的成员变量,但是对于内置数据类型,却表现未定义行为
C++中 const 定义的变量称为常变量。变量的形式,常量的作用,用作常量,常用于取代#define 宏常量
|
1
|
dynamic_cast<目标类型> (标识符) |
用于多态中的父子类之间的强制转化
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注米米素材网的更多内容!
原文链接:https://blog.csdn.net/qq_43414070/article/details/121021741
发表评论