c语言的this的精妙用法。类似实现c++ this的方法。

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;
}


 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值