qfedu-cpp-level/day7/d14.cpp

32 lines
593 B
C++

// 类型转换
#include <iostream>
using namespace std;
int test1()
{
float f = 97.5;
char c = static_cast<char>(f);
cout << "c = " << (int)c << endl;
}
int test2()
{
float f = 97.5;
// int *p = &f; // 指针转换不允许跨类型
// int *p = static_cast<int *>(&f);
// int *p = (int *)&f;
// int *p = dynamic_cast<int *>(&f);
float *pf = &f;
// double *p = const_cast<double *>(pf);
int *p = reinterpret_cast<int *>(pf); // 重新解释类型转换,不安全
cout << "*p = " << *p << endl;
}
int main()
{
test2();
return 0;
}