c++中的四种类型转换
#include <iostream>
//using namaspace std;
//C++中的四种类型转换
class A
{
public:
virtual void fn()
{
}
private:
};
class B:public A
{
public:
void fn()
{
}
private:
};
class C
{
public:
void fn()
{
}
private:
};
class D :public C
{
public:
void fn()
{
}
private:
};
int _tmain(int argc, _TCHAR* argv[])
{
// static_cast 用于基本类型之间的类型转换
float x = 10.3;
int y;
y = static_cast<int>(x);
// const_cast 用于常量类型转换 把const类型的指针或者引用转换为非const类型
int k = 5;
int const *const_x = &k;
int *noconst_x = const_cast<int*>(const_x);
//reinterpret_cast 重新解释类型转换,此标识符的意思即为数据的二进制形式重新解释,但是不改变其值。一般不常用
int i;
char *ptr="aaaa";
i=reinterpret_cast<int>(ptr);
//dynamic_cast 动态类型的转换该操作符用于运行时检查该转换是否类型安全,但只在多态类型时合法,
//dynamic_cast与static_cast具有相同的基本语法,static_cast转换的时候没有类型检查,因而不安全
dynamic_cast<A*> (new B);
dynamic_cast<B*> (new A);
dynamic_cast<C*> (new D);
dynamic_cast<D*> (new C);//类型检查错误
static_cast<A*> (new B);
static_cast<B*> (new A);
static_cast<C*> (new D);
static_cast<D*> (new C);
return 0;
}