问题描述
$ b我正在阅读有效的C ++由scott myers书。有关虚拟基类和虚拟继承的提到如下。
在上面的语句中,什么是初始化虚拟基本calsses的规则和什么是派生类必须采取的责任,如上文中提到的。请求以示例解释。
谢谢!
我以一个例子解释报价。假设你有这些类,
c> c> c> $ $> c $ c>,这就是为什么 B(x)和 C(x)甚至不编译。请参阅:
但是一旦你写了 A(x),它编译得很好。请参阅:
现在再次阅读报价,并注意粗体文本:
b $ b我希望这个解释可以帮助你理解这个概念!
Hi All, I am reading Effective C++ by scott myers books. It was mentioned about virtual base class and virtual inheritance as follows.
Question is in above statement what are the rules for initialization of virtual base calsses and what are the responsiblities that derivied class has to take as mentioned in above text. Kindly request to explain with example.
Thanks!
解决方案Let me explain the quotation by an example. Suppose, you've these classes,
struct A { A(int x) {} }; struct B : virtual A { B(int x) : A(x) {} }; struct C : virtual A { C(int x) : A(x) {} };Note: A is virtual base!
Now you define D deriving from B and C :
struct D : B, C { //correct constructor - because A(x) is "present" in the initialization-list D(int x) : A(x), B(x), C(x) { } //wrong constructor - because A(x) is "absent" from the initialization-list! //D(int x) :B(x), C(x) { } };Please note that D is the most derived class in the hierarchy, so the responsibility of initializing A is with D, that is why D explicitly writes A(x) in it's constructor initialization-list (see above). If you write only B(x) and C(x), then it would NOT even compile. See this: http://www.ideone.com/sO6m5
But once you write A(x), it compiles fine. See this: http://www.ideone.com/kiwh0
Now read the quotation again, and pay attention to the bold text:
I hope this explanation helps you understanding the concept!
这篇关于关于虚拟基类和C ++中的虚拟继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!