都知道,C++中類的成員變量和成員函數是分開存儲的,變量可以存儲在堆、棧、全局區,而函數只能存在代碼段,並且一個類只對應一套成員函數,那麼如何通過類對象調用成員函數呢?
答案是通過this指針,類對象將this指針傳遞給函數,所以函數能夠使用類對象的成員變量,而this指針保存的就是當前對象的地址。這個傳遞的行爲被編譯器隱藏起來了,下面通過C代碼模擬this指針的傳遞過程。
頭文件test.h
#ifndef _TEST_H_
#define _TEST_H_
typedef void Demo;//隱藏對外屬性,模擬private限定符
typedef struct test//定義類
{
int mi;
int mj;
}Test;
//定義類成員函數,通過參數可以看出來通過指針傳遞對象
Demo* Creat(int i, int j);//模擬構造函數,返回值爲模擬出來的this指針
int GetI(Demo* pThis);
int GetJ(Demo* pThis);
int Add(Demo* pThis, int k);
void Free(Demo* pThis);//模擬析構函數
#endif // _TEST_H_
test.c
#include "test.h"
#include <stdlib.h>
//函數中都是通過對象指針進行數據傳遞使用的
Demo* Creat(int i, int j)
{
Test* t = (Test*)malloc(sizeof(Test));
if( NULL != t)
{
t->mi = i;
t->mj = j;
}
return t;
}
int GetI(Demo* pThis)
{
Test *obj = (Test*)pThis;
return obj->mi;
}
int GetJ(Demo* pThis)
{
Test *obj = (Test*)pThis;
return obj->mj;
}
int Add(Demo* pThis, int k)
{
Test *obj = (Test*)pThis;
return obj->mi + obj->mj + k;
}
void Free(Demo* pThis)
{
if(NULL != pThis)
{
free(pThis);
}
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
int main()
{
Test *t = Creat(1, 2);
printf("getI = %d\n", GetI(t));
printf("getJ = %d\n", GetJ(t));
printf("Add = %d\n", Add(t, 3));
printf("Hello world!\n");
return 0;
}
通過此代碼顯式的展現了C++中this指針的傳遞過程。