zoukankan      html  css  js  c++  java
  • C语言对象化编程


    以下为一个引子:

    C中struct的函数实现,只能用函数指针成员。

    C结构体内不能有函数的代码,但可以有函数的指针。

    C/C code

    Code highlighting produced by Actipro CodeHighlighter (freeware)

    http://www.CodeHighlighter.com/

     

    #include <stdio.h>
    
    struct test
    {
        void fun()
        {
            printf("hello,world
    ");
        }
    };
    
    int main()
    {
        struct test _t;
        _t.fun();
        return 0;
    }



    上面的代码保存为.c, 在VC 6.0, Dev Cpp 里都通不过。
    函数指针方式实现,而不要直接定义函数 ...
    当然struct里能放函数指针的。比如这样:

    C/C code

    Code highlighting produced by Actipro CodeHighlighter (freeware)

    http://www.CodeHighlighter.com/

     

    #include <stdio.h>
    void fun()
    {
        printf("hello,world
    ");
    }
     
    struct test
    {
        void (*Fun)();
    };
     
    int main()
    {
        struct test _t;
        _t.Fun = fun;
     
        (*_t.Fun)();
        return 0;
    }
     


    C结构体内不能有函数的代码,但可以有函数的指针
    网友回复:纯C中的struct没有成员函数,但可以有函数指针。
    Object-oriented programming with ANSI-C是用函数指针来模拟成员函数的。

     

    参考:http://blog.sina.com.cn/s/blog_502d82e10100fgl1.html


    Linux的源代码中C语言对象化

    参考Linux内核的源代码中,有更好的使用


    #include<stdio.h>
    
    struct MyClass
    {
            char* name; 
    
            int age;
            void (*funnull) ();
            void (*func) (struct MyClass mc);
    };
    
    void realfunnull()
    {
            printf("hello world!
    ");
    }
    
    void realfunc(struct MyClass mc)
    {
            printf("MyClass's name is:%s
    ",mc.name);
            printf("MyClass's age is:%d
    ",mc.age);
    }
    
    int main()
    {
            struct MyClass mc = {"Simon", 25, realfunnull, realfunc};
            mc.funnull();
            mc.func(mc);
            return 0;
    }
    












  • 相关阅读:
    kafka那些事儿
    netty
    kafka为什么吞吐量高,怎样保证高可用
    通用mybatis单表操作接口
    P1058立体图
    P2258 子矩阵
    P1439 【模板】最长公共子序列(LCS)
    洛谷P2672 推销员
    P3373线段树2
    P5018 对称二叉树
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3289825.html
Copyright © 2011-2022 走看看