一句话总结:static_cast在编译时会进行类型检查,而强制转换不会。
zhaojunyandeMacBook-Pro:~ zhaojunyan$ g++ -o sc sc.cpp
sc.cpp:19:9: error: static_cast from 'A *' to 'B *', which are not related by
inheritance, is not allowed
B* p = static_cast<B*>(&a);
^~~~~~~~~~~~~~~~~~~
1 error generated.
zhaojunyandeMacBook-Pro:~ zhaojunyan$ cat sc.cpp
#include <iostream>
class A
{
public:
A(){}
~A(){}
};
class B
{
public:
B(){}
~B(){}
};
int main()
{
A a;
B* p1 = (B*)(&a);
B* p = static_cast<B*>(&a);
return 0;
}
zhaojunyandeMacBook-Pro:~ zhaojunyan$