强制类型转换
1.C语言中的类型转换
在C语言中,如果赋值运算符左右两侧类型不同,或者形参与实参类类型不匹配,或者返回值类型与接收返回值类型不一致时,就需要发送类型转换。C语言中总共有两种形式的类型转换:
1.隐式类型转换:编译器在编译阶段自动运行,不能转就编译失败。
2.显示类型转换:需要用户自己处理。
int main()
{
//隐式类型转换(相近类型,意义相似的类型)
int i = 10;
double d = 6.66;
i = d;
cout << i << endl;
//强制类型转换(不相近类型,意义差别很大的类型)
int* p = NULL;
p = (int*)i;
cout << p << endl;
return 0;
}
2.C++类型转换
1.static_cast
static_cast对应C语言隐式类型转换,意义相近的类型。
int main()
{
double d = 6.66;
int i = static_cast<int>(d);
cout << i << endl;
return 0;
}
2.reinterpret_cast
reinterpret_cast对于C语言大部分显示类型转换,意义不相近的类型。
int main()
{
int i = 6;
int* p = reinterpret_cast<int*>(i);
cout << p << endl;
return 0;
}
3.const_cast
const_cast对于C语言显示类型转换中去掉const属性的,意义不相近的类型。
int main()
{
const int i = 6;
int* p = const_cast<int*> (&i);
*p = 20;
cout << i << endl;
cout << *p << endl;
return 0;
}
4.dynamic_cast
dynamic_cast用于将一个父类对象的指针/引用转换为子类而对象的指针/引用。
class A
{
public:
virtual void func()
{
cout << "A::func()" << endl;
}
int a;
};
class B : public A
{
public:
void func()
{
cout << "B::func()" << endl;
}
};
void f_cast(A* pa)
{
B* pb = dynamic_cast<B*>(pa);
//如果pa是指向子类对象,转换成功
if (pb != nullptr)
{
pb->a = 10;
cout << "转换成功" << endl;
}
//如果pa是指向父类对象则失败返回nullptr
else
cout << "转换失败" << endl;
}
int main()
{
A a;
B b;
//dynamic_cast通过去虚表的上分存储的标识信息,来判断指向父类对象还是子类对象
A* pa = &a;
f_cast(pa);
pa = &b;
f_cast(pa);
return 0;
}
3.RTTI
RTTI:即运行时类型识别。
C++通过以下方式来支持RTTI:
1.typeid
2.dynamic_cast
3.decltype