以下前向声明的多继承指针转换代码如何工作?
在下面的代码中,指针如何转换&多重继承一起玩?
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);
}
我的理解有点动摇。
一方面,someWork 对 Bar 一无所知,所以这不应该起作用;但另一方面,我已经向前宣布了吧。
谢谢!
In the followint code, how does the pointer conversion & multi-inheritance play together?
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; but on the other hand, I have forward declared Bar.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是行不通的,而且它的作用也不完全是你想象的那样。 您对 c 风格的强制转换的使用
在这种情况下, 是不正确的。您想要做的是将
Bar*
向上转换为Foo*
(即,从指向派生类的指针执行static_cast
指向基类的指针)。然而,由于此时
Bar
的定义不可用,编译器不知道Foo
是Bar
的基类。因此,static_cast
失败,编译器回退并使用reinterpret_cast
,这根本不是一回事。This doesn't work and it isn't doing quite what you think it is. Your use of the c-style cast:
is incorrect in this case. What you are trying to do is upcast the
Bar*
to aFoo*
(i.e., perform astatic_cast
from a pointer to a dervied class to a pointer to a base class).Since the definition of
Bar
is not available at this point, however, the compiler does not know thatFoo
is a base class ofBar
. Thus, thestatic_cast
fails and the compiler falls back and uses areinterpret_cast
, which is not at all the same thing.唔。我的猜测是,由于在链接期间(即在类编译之后)对强制转换进行了“评估”。但这只是一个猜测。
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.