C语言中的类型转换
- 隐式类型
- 显示类型
int main()
{
int i = 3;
//隐式类型转换
double d = i;
printf("%d,%.2f\n", i, d);
int* p = &i;
//显示的强制类型转换
int add = (int)p;
printf("%x,%d\n", p, add);
system("pause");
return 0;
}
截图:
缺陷:转换的可视性差,所有的转换形式都以一种相同形式书写,难跟踪错误的转换。
C++强制类型转换
为了增加代码的可视性,C++引用了四种命名的强制类型类型转换操作符:
- static_cast
- reinterpret_cast
- const_cast
- dynamic_cast
static_cast
用于非多态类型的转换(静态转换),编译器隐式执行的任何类型转换都可用static_cast,但不能用于两个不相关的类型进行转换。
int main()
{
double d = 3.01;
int a = static_cast<int>(d);
cout << a << endl;
system("pause");
return 0;
}
reinterpret_cast
reinterpret_cast操作符通常为操作符的位模式提供较低层次的重新解释,用于将一种类型转化为另一种不同类型。
typedef void(*FUNC)();
int Fun(int i)
{
cout << "fun" << endl;
return 0;
}
void test()
{
FUNC f = reinterpret_cast<FUNC>(Fun);
f();
}
const_cast
最常用的用途就是删除变量的const属性,方便赋值
int main()
{
const int i = 2;
int* p = const_cast<int*> (&i);
*p = 3;
cout << *p << endl;
cout << i << endl;
system("pause");
return 0;
}
dynamic_cast用于将一个父亲对象的指针转换为子类对象的指针或引用。向上转换:子类对象指针->父类对象指针或引用;向下转换:父类对象指针->子类对象指针或引用。dynamic_cast只能用于含有虚函数的类;dynamic_cast会先检查是否转换成功,能成功则转换,不成功返回0。
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;
}
若非使用强制类型转换,则应限制强制类型转换值得作用域,以减少发生错误的机会。
explicit
explicit关键字阻止经过转换构造函数进行的隐式类型转换的发生
class A
{
public:
explicit A(int a)
{
cout << "A(int a)" << endl;
}
A(const A& a)
{
cout << "A(const A& a)" << endl;
}
private:
int _a;
};
int main()
{
A a1(1);
// 隐式转换-> A tmp(1); A a2(tmp);
//A a2 = 1;
}
为什么要需要四种类型转换
C语言中隐式类型转换可能会出问题;显示类型转换将所有情况混合在一起,代码不够清晰。
RAII
RAII为运行时类型识别。
typeid运算符,dynamic_cast运算符支持RAII。