[英]How does the following foward-declared multi-inheritance pointer converted code work?
In the followint code, how does the pointer conversion & multi-inheritance play together? 在followint代码中,指针转换和多继承如何一起发挥作用?
class Foo {
public:
virtual void someFunc();
};
class Bar;
void someWork(Bar *bar) {
((Foo*) bar)->someFunc();
}
class Bar: public Zed, public Foo {
...
virtual void someFunc() { ... do something else ... }
}
Bar bar;
int main() {
someWork(&bar);
}
My understanding is kinda shaky. 我的理解有点动摇。
On one hand, someWork knows nothing about Bar, so this shouldn't work; 一方面,someWork对Bar一无所知,所以这应该行不通。 but on the other hand, I have forward declared Bar. 但另一方面,我已经宣布了巴尔。
Thanks! 谢谢!
This doesn't work and it isn't doing quite what you think it is. 这是行不通的,它并没有完全按照您的想法进行。 Your use of the c-style cast: 您使用c样式的转换:
(Foo*) bar
is incorrect in this case. 在这种情况下是不正确的。 What you are trying to do is upcast the Bar*
to a Foo*
(ie, perform a static_cast
from a pointer to a dervied class to a pointer to a base class). 您要执行的操作是将Bar*
向上转换为Foo*
(即,从指向派生类的指针到指向基类的指针执行static_cast
)。
Since the definition of Bar
is not available at this point, however, the compiler does not know that Foo
is a base class of Bar
. 但是,由于此时Bar
的定义不可用,因此编译器不知道Foo
是Bar
的基类。 Thus, the static_cast
fails and the compiler falls back and uses a reinterpret_cast
, which is not at all the same thing. 因此, static_cast
失败,编译器后退并使用reinterpret_cast
,这根本不是同一件事。
Hmm. 嗯。 My guess is that since the cast is "evaluated" during linking, which is after the class has been compiled. 我的猜测是,由于转换是在链接期间(在类已编译之后)“求值”的。 But that's just a guess. 但这只是一个猜测。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.