英文:
Why is this cross-cast not allowed?
问题
我得到以下错误消息:
错误: 无法使用 static_cast 从 'Base1 *' 转换到 'Base2 *',它们之间没有继承关系
编译器应该有足够的信息来确定可以从 Derived
到达 Base2
,而不需要使用 RTTI(dynamic_cast
),并让我这样做:
Derived* foo3 = static_cast<Derived*>(foo1);
Base2* foo2 = foo3;
为什么不允许这样做呢?(可以争论编译器不知道 foo1
是否为 Derived
类型,但即使从例如 Base1
转换到 Derived
时,static_cast
也不会检查类型。)
英文:
Consider this simple example:
struct Base1 {};
struct Base2 {};
struct Derived : public Base1, public Base2 {};
int main()
{
Derived foo;
Base1* foo1 = &foo;
Base2* foo2 = static_cast<Base2*>(foo1);
}
I get:
Error: static_cast from 'Base1 *' to 'Base2 *', which are not related by inheritance, is not allowed
The compiler should have enough information to figure out that Base2
can be reached from Derived
without RTTI (dynamic_cast
) and having me to do:
Derived* foo3 = static_cast<Derived*>(foo1);
Base2* foo2 = foo3;
Why isn't this allowed? (One could argue that the compiler doesn't know if foo1
is of Derived
type, but static_cast
doesn't check the type anyway even when converting from Base1
to Derived
for example)
Note: This question is similiar to mine, but it's not quite the same because here we are cross-casting base classes, not derived ones
答案1
得分: 3
static_cast
会失败,因为非正式地说,Base1
和 Base2
没有关联。
然而,如果你的类是多态的,dynamic_cast
将起作用:你可以通过添加虚拟析构函数来实现:
struct Base1 {virtual ~Base1() = default;};
struct Base2 {virtual ~Base2() = default;};
struct Derived : Base1, Base2 {};
int main()
{
Derived foo;
Base1* foo1 = &foo;
Base2* foo2 = dynamic_cast<Base2*>(foo1);
}
在处理组合(即接口)时,从 Base1
到 Base2
的这种转型是惯用的。
英文:
A static_cast
will fail since, informally speaking, Base1
and Base2
are not related.
However a dynamic_cast
will work if your classes are polymorphic: which you can achieve by adding virtual destructors:
struct Base1 {virtual ~Base1() = default;};
struct Base2 {virtual ~Base2() = default;};
struct Derived : Base1, Base2 {};
int main()
{
Derived foo;
Base1* foo1 = &foo;
Base2* foo2 = dynamic_cast<Base2*>(foo1);
}
This casting from Base1
to Base2
is idiomatic when working with composition (i.e. interfaces).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论