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语言写面向对象。

  • 相关阅读:
    断开/删除 SVN 链接(.svn)的几种方法
    Android 中 ListView 常用属性合集
    Android 中 GridView 常用属性合集
    LeetCode-387-字符串中的第一个唯一字符
    LeetCode-374-猜数字大小
    LeetCode-290-单词规律
    LeetCode-278-第一个错误的版本
    LeetCode-383-赎金信
    LeetCode-367-有效的完全平方数
    LeetCode-350-两个数组的交集 II
  • 原文地址:https://www.cnblogs.com/lh03061238/p/12470686.html
Copyright © 2011-2022 走看看