以下前向声明的多继承指针转换代码如何工作?

发布于 2024-08-19 13:53:04 字数 419 浏览 3 评论 0原文

在下面的代码中,指针如何转换&多重继承一起玩?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怼怹恏 2024-08-26 13:53:04

这是行不通的,而且它的作用也不完全是你想象的那样。 您对 c 风格的强制转换的使用

(Foo*) bar

在这种情况下, 是不正确的。您想要做的是将 Bar* 向上转换为 Foo* (即,从指向派生类的指针执行 static_cast指向基类的指针)。

然而,由于此时 Bar 的定义不可用,编译器不知道 FooBar 的基类。因此,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:

(Foo*) bar

is incorrect in this case. What you are trying to do is upcast the Bar* to a Foo* (i.e., perform a static_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 that Foo is a base class of Bar. Thus, the static_cast fails and the compiler falls back and uses a reinterpret_cast, which is not at all the same thing.

最单纯的乌龟 2024-08-26 13:53:04

唔。我的猜测是,由于在链接期间(即在类编译之后)对强制转换进行了“评估”。但这只是一个猜测。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文