C++中的类型转换
1、C语言中的类型转换
分为隐式类型转换和显示类型转换
1.2、C语言中的类型转换存在缺陷
1、隐式类型转换可能出现未知错误
2、显示类型转换导致代码不够清晰
3、转换的可视性差,难以追踪错误
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
int i = 1;
double d = 1;//隐式类型转换
printf("%d %.2f\n", i, d);
int* p = &i;
int address = (int)p;//显示类型转换
printf("%x %d\n", p, address);
system("pause");
return 0;
}
2、static_cast
static_cast用于非多态类型的转换,编译器执行的任何类型转换都可用static_cast,但它不能用于两个不相关类型进行转换
#include <iostream>
using namespace std;
int main()
{
double d = 12.34;
int a = static_cast<int>(d);
cout << a << endl;
system("pause");
return 0;
}
3、reinterpret_cast
reinterpret_cast操作符通常为操作数的位模式提供较低层次的重新解释,用于将一种类型转换为另一种不同的类型
#include <iostream>
using namespace std;
typedef void (*FUNC)();
int doSomething(int i)
{
cout << "doSomething()" << endl;
return 0;
}
int main()
{
FUNC f = reinterpret_cast<FUNC>(doSomething);
f();
system("pause");
return 0;
}
4、const_cast
const_cast可以去掉变量的const属性
#include <iostream>
using namespace std;
int main()
{
const int a = 2;
int* p = const_cast<int*>(&a);
*p = 3;
cout << a << endl;
system("pause");
return 0;
}
5、dynamic_cast
dynamic_cast用于将一个父类对象的指针转换为子类对象的指针或引用(动态转换)
向上转型:子类对象指针->父类对象指针/引用(不需要转换,赋值兼容规则)
向下转型:父类对象指针->子类对象指针/引用(用dynamic_cast转型是安全的)
注:
1、dynamic_cast只能用于含有虚函数的类
2、dynamic_cast会先检查是否能转换成功,能成功转换则转换,否则返回0
3、强制类型转换会关闭或挂起正常的类型检查。
#include <iostream>
using namespace std;
class A
{
public:
virtual void f()
{
}
};
class B : public A
{
};
void fun(A* pa)
{
B* pb1 = static_cast<B*>(pa);
B* pb2 = dynamic_cast<B*>(pa);
cout << "pb1:" << pb1 << endl;
cout << "pb2:" << pb2 << endl;
}
int main()
{
A a;
B b;
fun(&a);
fun(&b);
system("pause");
return 0;
}
6、explicit关键字
explicit关键字是阻止经过转换构造函数进行隐式转换的发生
#include <iostream>
using namespace std;
class A
{
public:
explicit A(int a)
{
cout << "A(int a)" << endl;
}
A(const A& a)
{
cout << "A(const A& a)" << endl;
}
private:
int m_a;
};
int main()
{
A a1(1);
A a2 = 1;
system("pause");
return 0;
}
7、RTTI
RTTI(Run-time Type identification)运行时类型识别
C++通过typeid运算符和dynamic_cast运算符来支持RTTI