int i = 10, j = 1;
double slope1 = i / j; //一般的强制类型转换,编译器可能会报出警告
double slope2 = static_cast<double>(j) / j; //显式地强制类型
转换,编译器无警告
double num = 3.14;
void *p = # //任何非常量对象的地址都能存入void*
double *dp = static_cast<double*>(p); //将void*转换回初始的指针类型
const char *pc;
//正确,但是通过p写值是未定义的行为
char *p = const_cast<char*>(pc);
const char* cp;
//错误,static_cast不能去除const性质
char*q = static_cast<char*>(cp);
//正确,字符串常量值可以转换为string类型
static_cast<string>(cp);
//错误,const只能去除const性质,但是不能进行数据类型的转换
const_cast<string>(cp);
int *ip;char *pc = reinterpret_cast<char*>(ip);
int *ip;char *pc = reinterpret_cast<char*>(ip);//编译器虽然不报错,但是后果未定义string str(pc);
dynamic_ cast<type*>(e)
dynamic_ cast<type&> (e)
dynamic_ cast<type&&> (e)
class Base {
public:
virtual void foo() {} //必须含有虚函数,否则不能执行dynamic_cast
};
class Derived :public Base {};
int main()
{
Base *bp = new Base;
//成功返回Derived指针,失败返回0
if (Derived *dp = dynamic_cast<Derived*>(bp))
{
//使用dp指向的Derived对象
}
else
{
//使用bp指向的Base对象
}
return 0;
}
class Base {
public:
virtual void foo() {} //必须含有虚函数,否则不能执行dynamic_cast
};
class Derived :public Base {};
void f(const Base &b)
{
try {
//如果出错,将抛出bad_cast异常
const Derived &d = dynamic_cast<const Derived&>(b);
}
catch (bad_cast) {
}
}