struct A { virtual voID foo() = 0;};struct A2 { virtual voID foo() = 0;};struct B : public A2 { voID foo() { printf("test\n"); }};int main() { B* b = new B; ((A*)b)->foo();}
我意识到这是不好的做法,不应该这样做,但它一般是否有效?
解决方法 实践并不坏:它不起作用.它会做点好事.不太可能,崩溃.由于您正在调用 unspecified behaviour,因此全部允许.编辑您可以查阅编译器技术文档(请参阅ABI)以查找您可能依赖的特定于编译器的扩展.尝试使用
static_cast<A*>(b) // invalID static cast (compile error)dynamic_cast<A*>(b) // returns null pointer value (runtime)
你在做什么是有效的
> reinterpret_cast< A *>(b)
并且结果完全由您自己负责实施定义.
编辑纳瓦兹:相关标准段落:§5.2.10,条款
总结
7.
A pointer to an object can be explicitly converted to a pointer to a different object type.69 When a
prvaluev
of type “pointer to T1” is converted to the type “pointer to cv T2”,the result isstatic_cast<cv T2*>(static_cast<cv voID*>(v))
if both T1 and T2 are standard-layout types (3.9) and the alignment
requirements of T2 are no stricter than those of T1. Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yIElds the original pointer value. The result of any other such pointer conversion is unspecifIEd.
以上是内存溢出为你收集整理的C中不同类树之间的转换全部内容,希望文章能够帮你解决C中不同类树之间的转换所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)