zoukankan      html  css  js  c++  java
  • C结构体中的函数指针与函数

    C结构体中的函数指针与函数

    1. 函数指针
    一般的函数指针可以这么定义:
    int(*func)(int,int);
    表示一个指向含有两个int参数并且返回值是int形式的任何一个函数指针. 假如存在这样的一个函数:
    int add2(int x,int y)
    {
    return x+y;
    }
    那么在实际使用指针func时可以这样实现:
    func=&add2; //指针赋值,或者func=add2; add2与&add2意义相同
    printf("func(3,4)=%d"n",func(3,4));

    事实上,为了代码的移植考虑,一般使用typedef定义函数指针类型.
    typedef int(*FUN)(int,int);
    FUN func=&add2;
    func();

    2.结构体中包含函数指针

    其实在结构体中,也可以像一般变量一样,包含函数指针变量.下面是一种简单的实现.
    #include "stdio.h"
    struct DEMO
    {
    int x,y;
    int (*func)(int,int); //函数指针
    };
    int add2(int x,int y)
    {
    return x+y;
    }
    void main()
    {
    struct DEMO demo;
    demo.func=&add2; //结构体函数指针赋值
    printf("func(3,4)=%d"n",demo.func(3,4));
    }
    上面的文件保存为mytest.c,在VC6.0和gcc4中编译通过.

  • 相关阅读:
    网络爬虫基础练习
    综合练习:词频统计
    画图
    Hadoop综合大作业
    hive基本操作与应用
    理解MapReduce计算构架
    熟悉HBase基本操作
    爬虫大作业
    熟悉常用的HDFS操作
    数据结构化与保存
  • 原文地址:https://www.cnblogs.com/wqlblogger/p/1354260.html
Copyright © 2011-2022 走看看