类型转换
-
c语言风格
- (type) expression
- type (expression)
-
c++风格
- static_cast
- dynamic_cast
- reinterpret_cast
- const_cast
使用:xx_cast <type>(expression)
const_cast
#include <iostream>
using namespace std;
class Person {};
int main() {
const Person* p = new Person();
//两种写法没有差别
// const_cast 能说明之前的是const
Person* p1 = const_cast<Person*>(p);
Person* p2 = (Person*)p;
return 0;
}
dynamic_cast
#include <iostream>
using namespace std;
class Person {
virtual void run() {}
};
class Student:public Person{};
class Car{};
int main() {
Person* p1 = new Person();
Person* p2 = new Student();
cout << "p1 :" << p1 << endl;
cout << "p2 :" << p2 << endl;
//dynamic 只能用在多态中(有虚函数);用在指针中;会做安全检测,不安全的为0
//c风格不做安全检测
Student* stu1 = dynamic_cast<Student *>(p1); //不安全
Student* stu2 = dynamic_cast<Student *>(p2); //安全
cout << "stu1 :" << stu1 << endl;
cout << "stu2 :" << stu2 << endl;
//支持交叉转换,直接赋值给NULL
Car *car = dynamic_cast<Car *>(p2);
return 0;
}
static_cast
- 对比dynamic_cast,缺乏运行安全检测
- 不能交叉转换(不是同一继承体系的,无法转换)
- 常用于基本数据类型转换、非const转成const
- 适用范围较广
reinterpret_cast
- 没有任何类型检查和格式转换,仅仅是简单的二进制数拷贝
- 可以交叉转换
- 可以将指针和整数相互转换
#include <iostream>
using namespace std;
int main() {
int a = 10;
double b = reinterpret_cast<double&>(a);
int* p = reinterpret_cast<int*>(0x100);
return 0;
}
double的存储
符号位 | 阶位 | 位数 | |
---|---|---|---|
float | 1 | 8 | 23 |
double | 1 | 11 | 52 |
10 --> 1010 --> 1.010*2^3
符号位:0
阶位:3 --> 3+1023 --> 0100 0000 0010(前十二位) 因为指数可以为负,为了便于计算,规定都先加上1023
尾数:010
10(double) --> 0100 0000 0010 0100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
小端存储:0x00 00 00 00 00 00 24 40