class A
{
int a;
};
class B
{
int b;
};
class C : public A
{
int c;
};
int main()
{
B b;
C c;
A* p1 = (A*) &b; // 这句是c风格的强制类型转换,编译不会报错,留下了隐患
A* p2 = static_cast<A*>(&b); // static_cast在编译时进行了类型检查,直接报错
A* p3 = dynamic_cast<A*>(&b);
A* p4 = (A*) &c;
A* p5 = static_cast<A*>(&c);
A* p6 = dynamic_cast<A*>(&c);
return 0;
}
cast.cpp:22:31: error: invalid static_cast from type 'B*' to type 'A*'
cast.cpp:23:32: error: cannot dynamic_cast '& b' (of type 'class B*') to type 'class A*' (source type is not polymorphic)
{
int a;
};
class B
{
int b;
};
class C : public A
{
int c;
};
int main()
{
B b;
C c;
A* p1 = (A*) &b; // 这句是c风格的强制类型转换,编译不会报错,留下了隐患
A* p2 = static_cast<A*>(&b); // static_cast在编译时进行了类型检查,直接报错
A* p3 = dynamic_cast<A*>(&b);
A* p4 = (A*) &c;
A* p5 = static_cast<A*>(&c);
A* p6 = dynamic_cast<A*>(&c);
return 0;
}
/*
编译直接报错:
cast.cpp: In function 'int main()':cast.cpp:22:31: error: invalid static_cast from type 'B*' to type 'A*'
cast.cpp:23:32: error: cannot dynamic_cast '& b' (of type 'class B*') to type 'class A*' (source type is not polymorphic)
*/
应使用static_cast取代c风格的强制类型转换,较安全。
本文通过具体的C++代码示例对比了C风格的类型转换与现代C++中static_cast和dynamic_cast的区别。介绍了static_cast在编译期进行类型检查的安全性优势及dynamic_cast在运行时类型检查的特点。
1141

被折叠的 条评论
为什么被折叠?



