從零開始學C++之虛擬函式與多型(一):虛擬函式表指標、虛解構函式、object slicing與虛擬函式、C++物件模型圖
阿新 • • 發佈:2019-01-09
#include <iostream>
using namespace std;
class CObject
{
public:
virtual void Serialize()
{
cout << "CObject::Serialize ..." << endl;
}
};
class CDocument : public CObject
{
public:
int data1_;
void func()
{
cout << "CDocument::func ..." << endl;
Serialize();
}
virtual void Serialize()
{
cout << "CDocument::Serialize ..." << endl;
}
CDocument()
{
cout << "CDocument()" << endl;
}
~CDocument()
{
cout << "~CDocument()" << endl;
}
CDocument(const CDocument &other)
{
data1_ = other.data1_;
cout << "CDocument(const CDocument& other)" << endl;
}
};
class CMyDoc : public CDocument
{
public:
int data2_;
virtual void Serialize()
{
cout << "CMyDoc::Serialize ..." << endl;
}
};
int main(void)
{
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(); //mydoc物件強制轉換為CDocument物件,向上轉型
// 將派生類物件轉化為了基類物件
//vptr 指向基類的虛擬函式表
delete pmydoc;
return 0;
}
using namespace std;
class CObject
{
public:
virtual void Serialize()
{
cout << "CObject::Serialize ..." << endl;
}
};
class CDocument : public CObject
{
public:
int data1_;
void func()
{
cout << "CDocument::func ..." << endl;
Serialize();
}
virtual
{
cout << "CDocument::Serialize ..." << endl;
}
CDocument()
{
cout << "CDocument()" << endl;
}
~CDocument()
{
cout << "~CDocument()" << endl;
}
CDocument(const CDocument &other)
{
data1_ = other.data1_;
cout << "CDocument(const CDocument& other)"
}
};
class CMyDoc : public CDocument
{
public:
int data2_;
virtual void Serialize()
{
cout << "CMyDoc::Serialize ..." << endl;
}
};
int main(void)
{
CMyDoc mydoc;
CMyDoc *pmydoc = new CMyDoc;
cout << "#1 testing" << endl;
mydoc.func();
cout << "#2 testing"
((CDocument *)(&mydoc))->func();
cout << "#3 testing" << endl;
pmydoc->func();
cout << "#4 testing" << endl;
((CDocument)mydoc).func(); //mydoc物件強制轉換為CDocument物件,向上轉型
// 將派生類物件轉化為了基類物件
//vptr 指向基類的虛擬函式表
delete pmydoc;
return 0;
}