object slicing与虚函数

#include <iostream.h>

 

class CObject

{

public:

       virtual void Serialize() { cout<<"CObject::Serialize()/n/n";}

};

 

class CDocument:public CObject

{

public:

       void func()

       {

              cout<<"CDocument::func()"<<endl;

       //     Serialize();//这句代码主要是为了实现虚拟函数的调用

       }

       void Serialize() { cout<<"CDocument::Serialize()/n/n";}

};

 

class CMyDoc:public CDocument

{

public:

       void Serialize() { cout<<"CMyDoc::Serialize()/n/n";}

};

 

void main()

{

       CMyDoc mydoc;

       CMyDoc *pmydoc=new CMyDoc;

      

       cout<<"#1 testing"<<endl;

       mydoc.func();

      

       cout<<"#2 testing"<<endl;

       ((CDocument *)(&mydoc))->func();

      

       cout<<"#3 testing"<<endl;

       pmydoc->func();

      

       cout<<"#4 testing"<<endl;

       ((CDocument)mydoc).func();

}

 

运行结果1:(注释掉函数funcSerialize()的的情况)

#1 testing

CDocument::func()

#2 testing

CDocument::func()

#3 testing

CDocument::func()

#4 testing

CDocument::func()

 

运行结果2:(没注释的情况)

#1 testing

CDocument::func()

CMyDoc::Serialize()

 

#2 testing

CDocument::func()

CMyDoc::Serialize()

 

#3 testing

CDocument::func()

CMyDoc::Serialize()

 

#4 testing

CDocument::func()

CDocument::Serialize()

经过所谓的data slicing,本例的mydoc真正变成了一个完完全全的CDocument对象

你可能感兴趣的:(object slicing与虚函数)