一、 引入
定義一個類的對象,首先系統(tǒng)已經(jīng)給這個對象分配了空間,然后會調(diào)用構造函數(shù)。一個類有多個對象,當程序中調(diào)用對象的某個函數(shù)時,有可能要訪問到這個對象的成員變量。而對于同一個類的每一個對象,都是共享同一份類函數(shù)。對象有單獨的變量,但是沒有單獨的函數(shù),所以當調(diào)用函數(shù)時,系統(tǒng)必須讓函數(shù)知道這是哪個對象的操作,從而確定成員變量是哪個對象的。這種用于對成員變量歸屬對像進行區(qū)分的東西,就叫做this指針。事實上它就是對象的地址,這一點從反匯編出來的代碼可以看到。
二、分析
1、測試代碼:
view sourceprint?///////////////////////////////////////////////////
#include
using namespace std;
/////////////////////////////////////////////////////
class A
{
public:
A(char *szname)
{
cout<<"construct"<
name = new char[20];
strcpy(name, szname);
}
~A()
{
cout<<"destruct"<
delete name;
}
void show();
private:
char *name;
};
/////////////////////////////////////////////////////
void A::show()
{
cout<<"name = "<
}
/////////////////////////////////////////////////////
int main()
{
A a("zhangsan");
a.show();
system("pause");
return 0;
}