【发布时间】:2017-11-03 22:56:45
【问题描述】:
在this answer,出现了以下场景:
#include <cassert>
struct A {};
struct B { virtual ~B(){} };
struct AA{};
template <class T>
struct C : A, T {};
int main()
{
B * b = new C<B>;
AA * aa = new C<AA>;
assert(dynamic_cast<A*>(b));
assert(dynamic_cast<A*>(aa)); //this line doesn't compile, as expected
}
在 g++ 4.8.4 (Ubuntu) 上,它编译并且断言通过。我的问题是,这真的合法吗?我觉得你根本不应该能够 dynamic_cast 到非多态类,但我坦率地承认我不是这里发生的事情的专家。
当我尝试相反的方向时:
dynamic_cast<B*>((A*)(new C<B>));
它无法编译,说明“源类型不是多态的”。我觉得这是一条线索,但要找到属于当前指针所基于的类的非多态基类似乎仍然很困难(那句话有意义吗?)。
【问题讨论】:
-
按承诺投票。
-
@Bathsheba 有点令人沮丧的是,我一直在写这个问题,所以给我一个警告,标题似乎很主观,这个问题可能会被关闭:S:P
-
奇怪不是吗?然而,如此多的垃圾从网上溜走。
-
@SirGuy 也许“你”是一个触发词?
标签: c++ casting polymorphism