CPP类型转换
1 /* CPP类型转换 */
2
3 #include<iostream>
4 #include<stdio.h>
5
6 void main()
7 {
8 double db = 10.9
9 float fl = db;// 默认数据类型转换
10 std::cin.get();
11 }
12
13 //-----------------------------------------------
14
15 void main()
16 {
17 void *p = new int[10];
18 int *pint = (int *)p;// C风格
19 std::cin.get();
20 }
21
22 //-----------------------------------------------
23
24 // static_cast<需要转换的数据类型>(要转换的数据)基本类型的转换
25
26 void main()
27 {
28 int n = static_cast<int>(78.98);
29
30 printf("%d\n",98.87);//C
31 printf("%d\n",static_cast<int>(98.87));// C++
32
33 printf("%f\n",98);//C
34 printf("%d\n",static_cast<float>(98));// C++
35
36 int *p =static_cast(int *)(malloc(100));
37
38 std::cin.get();
39 }
40
41 //-----------------------------------------------
42
43
44 //const int num = 10,不能修改(可以修改无法生效,编译的时候不从内存里读)
45 //const int *p 指向变量限定权限 只读不可写
46 //const_cast 可以去掉常量指针属性
47 void main()
48 {
49 int num[3] ={1,2,3};
50 const int *p = num;
51 std::cout << *p << *(p+1) << *(p+2) << std::endl;
52 *p = 10;// 不能修改需要去掉const属性
53 *(p+1) = 30;// 不能修改需要去掉const属性
54
55 int *pnew = const_cast<int *>(p);// 去掉const属性
56 *pnew = 10;
57 }
58
59 //-----------------------------------------------
60
61 /* 指针类型转换 */
62 void main()
63 {
64 // 指针是强类型,类型决定了数据的解析方式,内存占多大
65 int num =3;
66 char *p = reintertpret_cast<char *>(&num);// reintertpret_cast 专业转换指针
67 for (int i=0;i<4;i++)
68 {
69 printf("%c,%d,%p\n",*(p+i),*(p+i),p+i);
70 }
71
72 std::cin.get();
73 }
74
75 // dynamic_cast 主要用于类的指针之间的转换
长风破浪会有时,直挂云帆济沧海
posted on 2015-05-31 15:34 Dragon-wuxl 阅读(490) 评论(0) 收藏 举报
浙公网安备 33010602011771号