zoukankan      html  css  js  c++  java
  • 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
    ", Demo_GetI(d));     // d->getI();
        printf("d.mj = %d
    ", Demo_GetJ(d));     // d->getJ();
        printf("Add(3) = %d
    ", 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语言写面向对象。

  • 相关阅读:
    python项目打包成exe
    sql同比环比计算
    七款好看文字样式纯css
    一站式智能芯片定制技术
    实战清除电脑上恶意弹出广告窗口
    GAAFET与FinFET架构
    MIPI多媒体接口
    Intel GPU实现游戏与数据中心
    芯片倒爷赚钱术
    Cache Memory技术示例
  • 原文地址:https://www.cnblogs.com/lh03061238/p/12470686.html
Copyright © 2011-2022 走看看