就《VC++深入詳解》第三章74頁的內容,視頻中,孫鑫老師講到(大意是),建立衍生類別對象的時候,基類建構函式中this是指的誰呢?是指的衍生類別對象!
對此,胡亂寫了個程式如下:(其中利用了虛函數的技術 )
#include <iostream>
using namespace std;
class base
{
public:
int i;
base();
//~base();
virtual void show() { cout << "this is base class show() /n";}
};
class derived : public base
{
public:
int i;
derived() ;
//~derived();
virtual void show() { cout << "this is derived class show() /n";}
};
base *p;
base::base()
{
cout << "in base /n";
p=this;
this->show();
p->show();
};
derived::derived() : base()
{
cout << "in derived /n";
this->show();
p->show();
};
derived od;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "in main() /n";
od.show();
p->show();
((derived *) p)->show(); //當不使用虛函數的時候,用來說明“強制”的轉換 。sorry習慣了C的寫法了。
//一個問題:這裡可以(reinterpret_cast<derived *>(p))->show();嗎? 試一試吧!
system("pause");
return 0;
}
執行結果是:
in base
this is base class show()
this is base class show()
in derived
this is derived class show()
this is derived class show()
in main()
this is derived class show()
this is derived class show()
this is derived class show()
請按任意鍵繼續. . .
當去掉base基類的virtual關鍵字的時候執行結果變成了:
in base
this is base class show()
this is base class show()
in derived
this is derived class show()
this is base class show()
in main()
this is derived class show()
this is base class show()
this is derived class show()
請按任意鍵繼續. . .
事情是否就清楚了呢?是否就佐證了基類對象的this指標,指示的是衍生類別了呢?
下面的例子:
#include <iostream>
using namespace std;
int base_size,derive_dsize;
class base
{
public:
int i;
base(int);
};
class derived : public base
{
public:
int i,j;
derived(int,int,int) ;
};
base::base(int a=1)
{
base_size = sizeof(*this);
cout << "in base /n";
};
derived::derived(int a=1,int b=2,int c=3) : base(a)
{
i=b;
j=c;
derive_dsize = sizeof(*this);
cout << "in derived /n";
};
derived oa ;
int main( )
{
cout<< "/nBase size : " << sizeof(base) << "/n";
cout<< "/nDerive size : " << sizeof(derived) << "/n/n";
cout<< "/nBase size : " << base_size << "/n";
cout<< "/nDerive size : " << derive_dsize << "/n/n";
system("pause");
return 0;
}
執行結果是:
in base
in derived
Base size : 4
Derive size : 12
Base size : 4
Derive size : 12
請按任意鍵繼續. . .
基類的成員函數中的this指標,指示的是這個基類產生對象。不是指示的這個基類的衍生類別對象。基類中成員函數中的this指標,與衍生類別的this指標,雖然它們的地址是相同的、雖然通過虛函數技術可以用基類指標,來調用衍生類別的函數(可以調用衍生類別的私人函數嗎?私人變數也可以訪問嗎?如果覺得好玩,一試便知!)、雖然也可以利用強制的類型轉換,使得基類指標它成為衍生類別對象的指標。但實質上,二者的類型是不同。
this指標的設計是為了(一份)成員函數,確能處理多個由這個類生產出來的對象而設計的。