7月10日面试题总结

c++的类型转换

  • static_cast
  • const_cast
  • dynamic_cast
  • reinterpret_cast

static_cast

可以实现C++中内置基本数据类型之间的相互转换。如果涉及到类的话,static_cast只能在有相互联系的类型中进行相互转换。父类转换为子类或子类转换为父类。如果是没有任何关系的类之间转换,编译会出错。

1
2
3
4
5
6
7
8
9
10
11
12
13
int c = static_cast<int>(9.77);

class A{};
class B :public A {}
class C{}

A * a = new A();

B * b;
C * c;

b = static_cast<B>(a); //正常执行
c = static_cast<C>(a); //编译出错,因为A和C之间无联系

const_cast

const_cast操作不能在不同的种类间转换。主要是用来去掉const属性,当然也可以加上const属性。主要是用前者,后者很少用。

去掉const属性:const_case (&num),常用,因为不能把一个const变量直接赋给一个非const变量,必须要转换。

加上const属性:const int k = const_case<const int>(j),一般很少用,因为可以把一个非const变量直接赋给一个const变量,比如:const int* k = j;

reinterpret_cast

在某些情况下,为了适应接口类型要求,需要将int转化成uint,double转化成int64_t等,但是经过这种转化之后可能会有数据损失。如果只是为了适应接口,最终还是希望读出原始数据,那么可以选用reinterpret_cast

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>  
#include <stdint.h>

int main()
{
int64_t i = 0;
double d = 1.1;

int64_t j = reinterpret_cast<int64_t&>(d);
double j2 = reinterpret_cast<double&>(j);

int64_t k = static_cast<int64_t>(d);
double k2 = static_cast<double>(k);

printf("org=%lf, reintterpret forw(double=>int64_t)=%ld\t, reintterpret back(int64_t=>double)=%lf\n", d, j, j2);
printf("org=%lf, static forw(double=>int64_t)=%ld\t, static back(int64_t=>double)=%lf\n", d, k, k2);
}

dynamic_cast

(1)其他三种都是编译时完成的,dynamic_cast是运行时处理的,运行时要进行类型检查。
(2)不能用于内置的基本数据类型的强制转换。
(3)dynamic_cast转换如果成功的话返回的是指向类的指针或引用,转换失败的话则会返回NULL。
(4)继承关系的类指针对象或引用之间转换和包含有虚函数之间对象指针的转换
(5)在类的转换时,在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的。在进行下行转换时,dynamic_cast具有类型检查的功能,比 static_cast更安全。