C++中四种类型转换是:static_cast、 dynamic_cast、 const_cast、 reinterpret_cast
在网上搜到这是有可能成为C++工程师面试题之一。
static_cast
1、用于基本的数据类型转换
2、用于多态时向上向下转换
示例:
//1、用于基本的数据类型转换
#include <iostream>
using namespace std;
//static_cast 基本数据类型转换
void example()
{
int a = 100;
char c = static_cast<char>(a);
char st_a = 'g';
int e = static_cast<int>(st_a);
cout << c << endl; //输出结果为d
cout << e << endl; //输出结果为103
}
int main()
{
example();
return 0;
}
//2、static_cast 多态向上向下转换
#include <iostream>
using namespace std;
//static_cast
class Person{};
class Man : public Person{};
class female : public Person{};
int main()
{
Person * p;//声明一个父类指针
Man * m = static_cast<Man *>(p);//利用static_cast转换,父类指针转成子类指针
female * f;
Person * p1 = static_cast<Person *>(f);//利用static_cast转换,子类指针转成父类指针
return 0;
}
const_cast
简单的理解,使用一个另外一个数据对象去代替const进行后续使用,也就是去掉const,但是并没有对原const内容进行修改
#include <iostream>
using namespace std;
int main()
{
const int c = 1;
const int * f = &c;
int * d = const_cast<int *>(f);
*d = 3;
cout << "c:" << c << endl;
cout << "*d:" << *d << endl;
return 0;
}
输出结果:
dynamic_cast
功能是子类转成父类,转换前会进行类型检查,不转换基本数据类型或没有继承关系的类型。
#include <iostream>
using namespace std;
class Person{};
class female : public Person{};
int main()
{
Person * p;//声明一个父类指针
female * f;
Person * p = dynamic_cast<Person *>(f);//子类指针转换成父类指针
return 0;
}
reinterpret_cast
暴力转换,例子
#include <iostream>
using namespace std;
class Dog{};
class Bird{};
//reinterpret_cast 强制类型转换
typedef void (*FUNC)(int, int);
typedef void (*FUNC2)(int, char *);
void example3()
{
//1、没有关联的两个类之间的转换
Dog* white_dog = NULL;
Bird * black_bird = reinterpret_cast<Bird *>(white_dog);
//2、函数指针转换
FUNC func1;
FUNC2 func2 = reinterpret_cast<FUNC2>(func1);
}
当然转换其他的更不用说。
据大神解释,reinterpret_cast的用意不是随心所欲的进行各种数据类型的转换,而是将其转换后仍然能安全地转换回原来的类型,它只是起到一个临时作用,相当于一个过渡。所以慎用