Virtual base derivation//virtual inheritance
#include <iostream>using namespacestd; #include<string>//--------------------------------------classa{ Public: intM_ax; intM_ay; A (); A (intVaintVY); voidshow ();}; A::a () {}a::a (intVxintvy) { This->m_ax =VX; This->m_ay =vy;}voida::show () {cout<<"A::show"<<Endl; cout<<"A::m_ax ="<<m_ax<<Endl; cout<<"A::m_ay ="<<m_ay<<Endl;}//--------------------------------------classB1:Virtual PublicA { Public: intm_b1x; B1 (); B1 (intAxintAyintbx);}; B1::b1 () {}B1::B1 (intAxintAyintb1x) {M_ax=Ax; M_ay=ay; M_b1x=b1x;}//---------------------------------------classB2:Virtual PublicA { Public: intm_b2x; B2 (); B2 (intAxintAyintb2x);}; B2::b2 () {}B2::B2 (intAxintAyintb2x) {M_ax=Ax; M_ay=ay; M_B2X=b2x;}//-------------------------------------classC: PublicB1, PublicB2 {//Virtual Base Inheritance Public: intm_cx; C (); C (intAxintAyintB1X,intb2x); voidshow ();}; C::c () {}c::c (intAxintAyintB1X,intb2x) {M_ax= ax;//because C's superior B1, B2 use virtual base inheritance A, so there is only one m_ax in Class C, will not produce two semantics. M_ay =ay; M_b1x=b1x; M_B2X=b2x;}voidc::show () {cout<<"c::show ()"<<Endl; cout<<"M_ax ="<<m_ax<<Endl; cout<<"M_ay ="<<m_ay<<Endl; cout<<"m_b1x ="<<m_b1x<<Endl; cout<<"m_b2x ="<<m_b2x<<Endl;}//--------------------------------------intMain () {C C1 (1,2,3,4 ); C1.show (); //show that is implemented in CC1. A::show ();//The show that inherits from a has only one, in the following three kinds of way access to is the same a::show ()C1. B1::show (); C1. B2::show (); cout<<"Addr C1. B1::m_ax ="<<& (C1. B1::m_ax) <<endl;//M_ax inherited from a only one, the three ways to access the same m_ax, the address is the same. cout<<"Addr C1. B2::m_ax ="<<& (C1. B2::m_ax) <<Endl; cout<<"Addr C1. A::m_ax ="<<& (C1. A::m_ax) <<Endl; cout<<"C1. B1::m_ax ="<<c1. b1::m_ax<<Endl; cout<<"C1. B2::m_ax ="<<c1. b2::m_ax<<Endl; cout<<"C1. A::m_ax ="<<c1. a::m_ax<<Endl; B1 B1 ( A, -, -) ; cout<<"B1.m_ax ="<<b1.m_ax<<Endl; B1.show ();//b Virtual Inheritance A, you can not rewrite a method and directly use. while(1); return 0 ;}//c::show ()//M_ax = 1//M_ay = 2//m_b1x = 3//m_b2x = 4// //A::show//A::m_ax = 1//A::m_ay = 2// //A::show//A::m_ax = 1//A::m_ay = 2// //A::show//A::m_ax = 1//A::m_ay = 2// //Addr C1. B1::m_ax = 0xbfbb43c8//because C's superior B1, B2 use virtual base inheritance A, so there is only one m_ax in Class C, will not produce two semantics. //Addr C1. B2::m_ax = 0xbfbb43c8//Addr C1. A::m_ax = 0xbfbb43c8//C1. B1::m_ax = 1//C1. B2::m_ax = 1//C1. A::m_ax = 1// //B1.m_ax =//A::show//A::m_ax =//A::m_ay =
Reference: Huaqing Vision notes.
C + +, virtual base derivation: A solution to the two semantics generated by common base classes