C语言写一个类

 

 

#ifndef _50_2_H_
#define _50_2_H_

typedef void Demo;

Demo* Demo_Create(int i, int j);
int Demo_GetI(Demo* pThis);
int Demo_GetJ(Demo* pThis);
int Demo_Add(Demo* pThis, int value);
void Demo_Free(Demo* pThis);

#endif

 

#include "50-2.h"
#include "malloc.h"

struct ClassDemo
{
    int mi;
    int mj;
};

Demo* Demo_Create(int i, int j)
{
    struct ClassDemo* ret = (struct ClassDemo*)malloc(sizeof(struct ClassDemo));
    
    if( ret != NULL )
    {
        ret->mi = i;
        ret->mj = j;
    }
    
    return ret;
}

int Demo_GetI(Demo* pThis)
{
     struct ClassDemo* obj = (struct ClassDemo*)pThis;
     
     return obj->mi;
}

int Demo_GetJ(Demo* pThis)
{
    struct ClassDemo* obj = (struct ClassDemo*)pThis;
     
    return obj->mj;
}

int Demo_Add(Demo* pThis, int value)
{
    struct ClassDemo* obj = (struct ClassDemo*)pThis;
     
    return obj->mi + obj->mj + value;
}

void Demo_Free(Demo* pThis)
{
    free(pThis);
}

 

#include <stdio.h>
#include "50-2.h"

int main()
{
    Demo* d = Demo_Create(1, 2);             // Demo* d = new Demo(1, 2);
    
    printf("d.mi = %d\n", Demo_GetI(d));     // d->getI();
    printf("d.mj = %d\n", Demo_GetJ(d));     // d->getJ();
    printf("Add(3) = %d\n", Demo_Add(d, 3));    // d->add(3);
    
    // d->mi = 100;
    
    Demo_Free(d);
    
    return 0;
}

ClassDemo代表一个类,Demo_Create相当于构造函数。

运行结果如下:

 

 主函数第12行直接通过d指针修改mi的值,会编译报错:

 

 

从面向对象的观点来看,mi是私有的,我们不能从外部访问。

而在C语言中没有private关键字,我们是通过void*指针来实现的。通过void这样的技术来实现信息隐藏。

面向对象不是C++专属的,我们也可以用C语言写面向对象。

posted on 2020-03-12 17:37  lh03061238  阅读(773)  评论(0编辑  收藏  举报

导航