#include<iostream>
using namespace std;
class X
{
int a;
int b;
public:
void f(int a)
{
cout<<"\nInside X";
}
virtual void abc()
{
cout<<"\nHello X";
}
};
class Y : public X
{
int a;
public:
void f(int a, int b)
{
cout<<"\nInside Y";
}
void abc()
{
cout<<"\nHello Y";
}
};
int main()
{
X a;
cout<<sizeof(X);
Y b;
cout<<sizeof(Y);
X *h = new Y;
h->abc();
}
據我所知,類X的大小爲12字節的原因是因爲它包含一個虛擬表的vptr(虛擬指針)。無論如何,我可以閱讀這個虛擬表,如果沒有,至少可以訪問虛擬指針。我試過使用工會,但它給了我一些錯誤。理解虛函數的麻煩
而且,當我打電話H-> ABC(),它是如何知道的類的對象,h
指向?我認爲這大部分是在編譯時完成的。但是當你有一個指向派生類的基類指針時,它如何知道要執行哪個類函數。 考慮這兩種情況
X *h = new X;
h->abc();/* This would call the abc function in X */
和
X *h = new Y;
h->abc();/* This would call the abc function in Y*/
我看了,那h
指針會去它指向的對象的虛函數表,並會因此調用該函數?但是,這在運行時如何實現?
我會編輯最後一個問題,因爲它不會與討論主題一起進行。但我相信前兩個問題都在本次討論的範圍之內。 – user2560730