C中struct的函数的实现

 

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\n");

    }

};


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\n");

}

 

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值