[英]why this pointer value changed after adding virtual keyword in C++
考慮下面的代碼行
#include<iostream>
using namespace std;
class base
{
int i;
public:
void printb()
{
cout << "This pointer of base "<<this<<endl;
}
};
class derived: public base
{
int i;
public:
void printd()
{
cout << "This pointer of derived "<<this<<endl;
}
};
main()
{
derived d1;
d1.printd();
d1.printb();
}
在64位ubuntu機器上用g ++(4.8.4)編譯后,結果是
This pointer of derived 0x7ffe74697ac0
This pointer of base 0x7ffe74697ac0
根據我的理解,由於我們使用單個對象進行調用,因此該基本指針和派生指針都是相同的。 我在派生類的printd()函數中添加了虛擬關鍵字,如下所示
#include<iostream>
using namespace std;
class base
{
int i;
public:
void printb()
{
cout << "This pointer of base "<<this<<endl;
}
};
class derived: public base
{
int i;
public:
virtual void printd()
{
cout << "This pointer of derived "<<this<<endl;
}
};
main()
{
derived d1;
d1.printd();
d1.printb();
}
上面代碼的輸出如下
This pointer of derived 0x7ffee969b1d0
This pointer of base 0x7ffee969b1d8
即使使用單個對象調用, 此指針值在派生基數和基數中也不同。每次我運行程序時,派生此指針與基數此指針之間存在1byte的差異。 誰能告訴為什么在這個指針這種差異和關鍵字如何影響虛擬this指針。
通過添加virtual
關鍵字,可以使derived
多態。 運行時多態性的常見實現是向對象的開頭添加一個指針。 該vptr指向動態分配的函數表 (通常稱為vtable )。
這樣,不是多態的base
子對象通過隱藏的指針在derived
超對象內部偏移。
您會看到指針自動調整,因為編譯器會在調用成員函數時注入代碼以執行此調整。 這確保了printb
將訪問所有的(潛在的)成員base
在正確的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.