1)内存空间不同大小的基础类型可以强制类型转换,但是会丢失精度
示例代码
#include <cstdio>
#include <iostream>
using namespace std;
int main(){
int a;
char c = '0';
a = (int)c;
printf("%d\n", a);
int d = 48;
char e = (char)d;
printf("%c\n", e);
return 0;
}
2)***内存空间不同大小的非基础数据类型不能强制转换,实质是不存在适当的转换函数
#include <cstdio>
#include <iostream>
using namespace std;
struct pk{
int d;
int a;
};
int main(){
pk b;
int destory = (int)b;
return 0;
}
数据大小相同的数据类型就可以进行强制类型转换,即使这两种数据类型是指针与结构体或者int等基础变量。
#include <cstdio>
#include <iostream>
using namespace std;
struct pk{
int d;
int a;
};
int main(){
/*
pk b;
int destory = (int)b;
*/
int a = 6;
int *b = &a;
int c = (int)b;
printf("%d %d\n", a, c);
return 0;
}
强制类型转换并不能改变内存中实际存储的内容
#include <iostream>\
#include <csrdio>
using namespace std;
int main(){
int a = -4;
printf("Before convert, the number of a is %d\n", a);
//int *p = &a;
int *p = (int *)a;
a = (unsigned int)a;
//(cout << "test") << " kk" << endl;
(cout << "After convert the number of point to the a memory is ") << a << endl;
(cout << "After convert the number of point to the a memory is ") << (unsigned int )a << endl;
return 0;
}