C++オブジェクトモデルについて考える

1980 ワード

一、私たちはまず一つの例を見て、1つの孫類は2つの父類を継承して、2つの父類は同時に同じおじいさん類を継承します.
#include <iostream>
using namespace std;
 
class Parent
{
public:
      int p_;                                           // p          ,         
      Parent(int p):p_(p)
      {
               cout<<"Parent ..."<<endl;
      }
};

 

class Child1 :virtual public Parent
{
public:
      Child1(int p) : Parent(p)
      {
             cout<<"Child1 ..."<<endl;
             p_ =3;                         // p   Child1     12
      }

      virtual void display()
	{
		cout<<"Child1  display"<<endl;
	}
};


class Child2 :virtual public Parent
{
public:
      Child2(int p) : Parent(p)
      {
               cout<<"Child2 ..."<<endl;
               p_=5;                       // p   Child2     13
              
      }

	virtual void display()
	{
		cout <<"Child2 display"<<endl;
	}
};

 

class GrandChild : public Child1, public Child2
{
public:
      int grandchild;

      // p      GrandChild ,     12,  13 ?        
      GrandChild(int p) : Child2(p),Child1(p),Parent(p)
      {
	       cout<<"GrandChild ..."<<endl;
               grandchild = 14;
      }

    virtual void display()
	{
		cout<<"GrandChild display"<<endl;
	}
};

 

int main(void)
{
      Child1* pGC = new GrandChild(4);
      pGC->display();
      delete pGC;
      return 0;

}

結果:
Parent ...
Child1 ...
Child2 ...
GrandChild ...
GrandChild display

Child 1*pGC=new GrandChild(4);Child 2*pGC=new GrandChild(4);では、プログラムが間違っています.
class GrandChild:public Child 1、public Child 2をclass GrandChild:public Child 2、public Child 1に変更します.
ではChild 2*pGC=new GrandChild(4);正常に実行されます.Child1* pGC = new GrandChild(4);実行エラー.
  
なぜか、私も知らないが、この例からC++オブジェクトモデルを学ぶことの重要性を感じさせた.C++オブジェクトモデルを知っていれば、上の問題は解決したと思います.