c++ 中没有虚函数的多重继承

发布于 2024-10-24 01:30:16 字数 942 浏览 5 评论 0原文

我遇到了钻石问题,并用一颗钻石找到了针对不同情况的不同解决方案。但是我找不到“链接”钻石的解决方案。

根据结构:是的,我每次都想有多个基类,所以虚拟继承不是一个解决方案(那么它甚至被称为钻石吗?)。我还想避免对钻石的每个中间层使用 get/set 函数。

p   p
|   |
k   k
 \ /
  s

class parent { int val; };
class kid1 : public parent {};
class kid2 : public parent {};
class school : public kid1, public kid2 {};

现在在父类中访问 val 的工作方式如下:

school* s = new school;
s->kid1::val=1; // works

但是下一个“链接”菱形又如何:

p   p   p   p
|   |   |   |
k   k   k   k
 \ /     \ /
  s       s
  |       |
  c       c
    \   /
      w

class country1 : public school {};
class country2 : public school {};
class world : public country1, public country2 {};

通过以下方式访问 val:

world* w = new world;
w->country1::kid1::val=1; // error

会导致:

error: ‘kid1’ is an ambiguous base of ‘world’

为什么?通向价值的途径不是已经明确定义了吗?

I came across the diamond problem and found different solutions for different cases with a single diamond. However I couldn't find a solution for 'chained' diamonds.

According to the structure: yes, I want to have multiple baseclasses everytime, so virtual inheritance isn't a solution (is it even called diamond then?). I also wanted to avoid get/set-functions for every middle-layer of a diamond.

p   p
|   |
k   k
 \ /
  s

class parent { int val; };
class kid1 : public parent {};
class kid2 : public parent {};
class school : public kid1, public kid2 {};

Accessing val in the parent class works now like follows:

school* s = new school;
s->kid1::val=1; // works

But what about the next 'chained' diamond:

p   p   p   p
|   |   |   |
k   k   k   k
 \ /     \ /
  s       s
  |       |
  c       c
    \   /
      w

class country1 : public school {};
class country2 : public school {};
class world : public country1, public country2 {};

Accessing val via:

world* w = new world;
w->country1::kid1::val=1; // error

results in:

error: ‘kid1’ is an ambiguous base of ‘world’

Why? Isn't the route to the value well defined?

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

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

发布评论

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

评论(2

慕烟庭风 2024-10-31 01:30:16

s->kid1::val 并不意味着“来自 kid1 子对象的 val”。它只是一个由包含它的类型(而不是子对象)限定的名称。

我不知道为什么 country1::kid1 甚至被接受,但显然它是 ::kid1 的 typedef。 world 中的两个数据成员都具有限定名称 ::kid1::val

你想要的是:

world* w = new world;
country1* const c1 = world;
c1->kid1::val = 1;

s->kid1::val does not mean "val from the kid1 subobject". It's just a name qualified by the type (not the subobject) that contains it.

I don't know why country1::kid1 is even accepted at all, but apparently it's a typedef for ::kid1. Two data members in world both have the qualified name ::kid1::val.

What you want is:

world* w = new world;
country1* const c1 = world;
c1->kid1::val = 1;
居里长安 2024-10-31 01:30:16

这是。该错误是由于编译器中的错误造成的。

It is. The error is due to a bug in your compiler.

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