c++ 中的虚拟继承是什么?
假设我有这样的代码:
class A {
};
class B: virtual public A {
};
class C: virtual public A {
};
class D: public B,public C, virtual public A {
};
如果D
继承B
和C
,虚拟继承可以保证A
只有一份副本code> 包含在 D
中;但是如果 D
再次使用 virtual public A
继承 A
会怎样,就像上面的代码一样?
是否会有一个或两个 A
类型的子对象?
我仍然对一些带有虚拟继承的表达式感到困惑。 例如:
#include <iostream>
using namespace std;
class A {
public:
A() {std::cout<<"A ";}
};
class B: A {
public:
B() {std::cout<<"B ";}
};
class AToo: virtual A {
public:
AToo() {
std::cout<<"AToo ";
}
};
class ATooB: virtual AToo, virtual B {
public:
ATooB() {
std::cout<<"ATooB ";
}
};
virtual
关键字能否保证ATooB
中只有一份A
的副本?如果 AToo
使用虚拟继承从 A
继承,但 B
没有,会发生什么? ATooB
中会有两份副本吗?这是否意味着 B
和 AToo
都应该对 A
使用虚拟继承,以确保 ATooB
仅具有一份?
Suppose I have this code:
class A {
};
class B: virtual public A {
};
class C: virtual public A {
};
class D: public B,public C, virtual public A {
};
If D
inherits B
and C
, virtual inheritance can ensure there is only one copy of A
contained in D
; but what if D
inherits A
using virtual public A
again, like in the code above?
Will there be one sub-object of type A
, or two?
I am still confused about some expressions with virtual inheritance.
for example:
#include <iostream>
using namespace std;
class A {
public:
A() {std::cout<<"A ";}
};
class B: A {
public:
B() {std::cout<<"B ";}
};
class AToo: virtual A {
public:
AToo() {
std::cout<<"AToo ";
}
};
class ATooB: virtual AToo, virtual B {
public:
ATooB() {
std::cout<<"ATooB ";
}
};
can the virtual
keyword ensure that there is only one copy of A
in ATooB
? if AToo
inherits from A
using virtual inheritance, but B
does not, what will happen? Will there be two copies in ATooB
? Does this imply that both B
and AToo
should use virtual inheritance for A
in order to ensure that ATooB
has only one copy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一 - 这是虚拟继承的预期用途。
A
只有一份副本。您实际上可以轻松验证这一点。为
A
提供一个成员并使用D
实例修改它。如果A
有多个副本,编译器会说访问不明确。编辑在编辑的问题中,将有 A 的两个副本。每次定期继承
A
时(没有虚拟
),都会有一个新的 A 副本A已制作完成。如果您想要一份副本,请每次都将其声明为虚拟
。One - that's the intended use of
virtual
inheritance. There is only one copy ofA
.You can actually verify that easily. Give
A
a member and modify it using aD
instance. If there was more than one copy ofA
, the compiler would say that the access is ambiguous.Edit in the edited question, there will be two copies of A. Each time
A
is inherited regularly (withoutvirtual
), a fresh copy of A is made. If you want one copy, declare itvirtual
every time.来自标准文档,10.1.4,
所以是的,只有一个。
From standard docs., 10.1.4,
And so yes, just one.