c语言的this的相关用法,细心体会。以后在c语言的数据结构和算法可以解耦使用。使用这个方法很强大 。
先谈实现此方法的逻辑
#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_
#include <stdio.h>
#include <stdlib.h>
#include "test.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);
}
}
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;
}