多重继承问题的基指针偏移调整

发布于 2025-01-09 12:26:36 字数 672 浏览 3 评论 0原文

我知道在这种情况下会发生基本偏移调整

class Mother {
 public:
  virtual void MotherMethod() {}
  int mother_data;
};

class Father {
 public:
  virtual void FatherMethod() {}
  int father_data;
};

class Child : public Mother, public Father {
 public:
  virtual void ChildMethod() {}
  int child_data;
};
Father *f = new Child;

在编译期间,这段代码相当于

Child *tmp = new Child;
Father *f = tmp ? tmp + sizeof(Mother) : 0;

我的问题是这个偏移量在编译阶段是如何确定的? 例如,在下面的情况下,

void fun(Father* f) {
    // do something
}

我们不知道指针将接收什么对象,如何确定编译过程中是否需要调整偏移量或需要调整多少偏移量。

希望有人能解答我的疑惑,非常感谢!

I know base offset adjustment will happen in this situation

class Mother {
 public:
  virtual void MotherMethod() {}
  int mother_data;
};

class Father {
 public:
  virtual void FatherMethod() {}
  int father_data;
};

class Child : public Mother, public Father {
 public:
  virtual void ChildMethod() {}
  int child_data;
};
Father *f = new Child;

During compilation, this code is equivalent to

Child *tmp = new Child;
Father *f = tmp ? tmp + sizeof(Mother) : 0;

My question is how this offset is determined in the compilation phase?
for example, in the following case

void fun(Father* f) {
    // do something
}

we don't know what object the pointer will receive, how is it possible to determine whether or how much offset adjustment is needed during compilation.

I hope someone can answer my doubts, Thank you very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

梦太阳 2025-01-16 12:26:36

函数的调用者确切地知道涉及哪些类型并进行必要的调整。

也就是说,

Child c;
fun(&c);

行为完全相同

Child c;
fun(static_cast<Father*>(&c));

,但转换是隐式的。

The caller of a function knows exactly what types are involved and does the necessary adjustments.

That is,

Child c;
fun(&c);

behaves exactly the same as

Child c;
fun(static_cast<Father*>(&c));

but the conversion is implicit.

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