c++ 中没有虚函数的多重继承
我遇到了钻石问题,并用一颗钻石找到了针对不同情况的不同解决方案。但是我找不到“链接”钻石的解决方案。
根据结构:是的,我每次都想有多个基类,所以虚拟继承不是一个解决方案(那么它甚至被称为钻石吗?)。我还想避免对钻石的每个中间层使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
s->kid1::val
并不意味着“来自kid1
子对象的val
”。它只是一个由包含它的类型(而不是子对象)限定的名称。我不知道为什么
country1::kid1
甚至被接受,但显然它是::kid1
的 typedef。world
中的两个数据成员都具有限定名称::kid1::val
。你想要的是:
s->kid1::val
does not mean "val
from thekid1
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 inworld
both have the qualified name::kid1::val
.What you want is:
这是。该错误是由于编译器中的错误造成的。
It is. The error is due to a bug in your compiler.