#include<iostream> void main() { void *p=NULL; int *pp=p; }
//ok #include<iostream> void main() { int *pp=NULL; void *p=pp; }
例子如下:
#include <iostream> using namespace std; class A { public: int m_a; }; class B: public A { public: int m_b; }; class C { public: int m_c; }; void f(A &a) { cout<<"f is called"<<endl; } void main() { B b; C c; f(static_cast<A &>(b));//static_cast的一大作用:子类对象b转化为父类对象,可以通过编译 f(static_cast<A &>(c));//进行了类型检查,类A和类C是毫无关系的,检查出错,不能通过编译 }
static_cast和dynamic_cast的不同
例子如下:三个类的定义同上
void main() { B b; C c; B & ref_b=reinterpret_cast<B &>(c); f(static_cast<A &>(ref_b));//成功欺骗编译器,编译通过,成功运行 //f(dynamic_cast<A &(ref_b));//编译通过,但是运行时检查了ref_b的实际类型为B,所以运行失败 }
void main() { B b; C c; A & ref_b=reinterpret_cast<A &>(c); f(ref_b);//成功欺骗编译器,编译通过,成功运行 }
在应用多态编程时,当我们无法确定传过来的对象的实际类型时使用dynamic_cast:如我们并不能确定传入的ref_b到底是B类型还是C类型(c通过reinterpret_cast转换为b,编译器并不知情),这时就应该用dynamic_cast。
void main() { B b; C c; B & ref_b=reinterpret_cast<B &>(c); f(static_cast<A &>(ref_b));//成功欺骗编译器,编译通过,成功运行 //f(dynamic_cast<A &(ref_b));//编译通过,但是运行时检查了ref_b的实际类型为B,所以运行失败 }
如果能保证对象的实际类型,用static_cast就可以了。至于reinterpret_cast,我很喜欢,很象c语言那样的暴力转换:)
原文:http://www.cnblogs.com/yexuannan/p/3683910.html