标签:变量类型 erro 转换 unsigned class expr long express 只读
语法:C中在变量名或具体数值前使用()表示进行强制类型转换;
(Type) Expression
Type(Expression)
注:
1 #include <stdio.h> 2 3 struct TS 4 { 5 int i; 6 int j; 7 }; 8 9 struct TS ts; 10 11 int main() 12 { 13 short s = 0x1122; 14 char c = (char)s; 15 int i = (int )s; 16 int j = (int)3.14; 17 unsigned int p = (unsigned int)&ts; //32位正常 64位截断 18 long l = (long)ts; 19 ts = (struct TS)l; 20 21 printf("s = %x\n", s); 22 printf("c = %x\n", c); 23 printf("i = %x\n", i); 24 printf("j = %x\n", j); 25 printf("p = %x\n", p); 26 printf("&ts = %p\n", &ts); 27 28 return 0; 29 }
编译器主动进行的类型转换即隐式类型转换;
称某类型在内存中所占用的字节数少为类型。则相应的,低类型向高类型的隐式类型转换时安全的,相反地,则类型转换将产生不正确的结果;
发生时机:
1 #include <stdio.h> 2 3 int main() 4 { 5 char c = ‘a‘; 6 int i = c; 7 unsigned int j = 0x11223344; 8 short s = j; 9 10 printf("c = %c\n", c); 11 printf("i = %d\n", i); 12 printf("j = %x\n", j); 13 printf("s = %x\n", s); 14 printf("sizeof(c + s) = %d\n", sizeof(c + s)); //char → int shor → int sizeof(int+int) = int; 15 16 return 0; 17 }
char/short → int → unsigned int → long → unsigned long → float → double
char → short
如1.1中所示,C语言中强制类型转换在任意类型之间都可以进行转换,编译器很难判断正确性,C++中的强制类型转换分为4种不同类型:
用于基本类型间转换
不能用于基本类型指针间的转换
用于有继承关系类对象之间的转换和类指针之间的转换
1 #include<stdio.h> 2 3 int main() 4 { 5 int i = 0x12345; 6 char c = ‘c‘; 7 int* pi = &i; 8 char* pc = &c; 9 10 c = static_cast<char>(i); 11 pc= static_cast<char*>(pi); //error 12 13 return 0; 14 }
用于去除变量的只读属性
强制类型转换的目标类型必须是指针或引用
1 #include<stdio.h> 2 3 int main() 4 { 5 const int& j = 1; 6 int& k = const_cast<int&>(j); //k = 1 7 8 const int x = 2; //x = 2常量 9 10 int& y = const_cast<int&>(x); //y = 2 11 int z = const_cast<int>(x); //error 12 13 k = 5; 14 15 printf("k = %d\n", k); //k=5 16 printf("j = %d\n", j); //j=5 17 18 y = 8; 19 20 printf("x = %d\n", x); //x = 2 21 printf("y = %d\n", y); //y = 8 22 printf("&x = %p\n", &x); 23 printf("&y = %p\n", &y); 24 25 return 0; 26 }
用于指针类型间的强制转换
用于整数和指针类型间的强制转换(嵌入式代码)
1 #include<stdio.h> 2 3 int main() 4 { 5 int i = 0; 6 char c = ‘c‘; 7 int* pi = &i; 8 char* pc = &c; 9 10 pc = reinterpret_cast<char*>(pi); 11 pi = reinterpret_cast<int*>(pc); 12 pi = reinterpret_cast<int*>(i); 13 c = reinterpret_cast<char>(i); //error 14 15 return 0; 16 }
用于有继承关系的类指针间的转换
用于有交叉关系的类指针间的转换
具有类型检查的功能(若转换不成功反馈NULL)
需要虚函数的支持
1 #include<stdio.h> 2 3 int main() 4 5 { 6 7 int i = 0; 8 int pi = &i; 9 10 char* pc = dynamic_cast<char*>(pi); //error 11 12 return 0; 13 }
标签:变量类型 erro 转换 unsigned class expr long express 只读
原文地址:https://www.cnblogs.com/Shuqing-cxw/p/9650942.html