justwant 发表于 2008-6-23 18:19

结构体内定义函数怎么编译报错

#include<stdio.h>
struct stu
{
   int id;
   int age;
   int gd;
   int exit(void);
};
struct stu s;
struct stu *p;
p=&s;


int main()
{  
  printf("%d",p->exit);
  return 0;
   
}
int exit(void)
{
     int k=20;
     return k;
}
field `exit' declared as a function

smltq 发表于 2008-6-23 18:22

struct stu
{
   int id;
   int age;
   int gd;
   int exit(void);//???
};

benyu1107 发表于 2008-6-23 18:41

我也同意ls的……

justwant 发表于 2008-6-23 18:46

[tk33]
那请问要怎么在结构体内定义一个函数

StarWing83 发表于 2008-6-23 18:49

int stu::exit(void)
{
     int k=20;
     return k;
}

  printf("%d",p->exit());

StarWing83 发表于 2008-6-23 18:53

p=&s;这行语句麻烦写在main里面……

justwant 发表于 2008-6-23 19:02

那C里面没有::,那怎么定义[tk37]

StarWing83 发表于 2008-6-23 19:24

你也知道没有啊
那你还这么写?

justwant 发表于 2008-6-23 19:33

那要在结构体里面定义一个函数成员,怎么定义啊?
或者定义一个指向函数的指针也可以啊

かわい 发表于 2008-6-23 19:58

麻烦你学C++


[color=white]<[img]http://yzfy.byethost18.com/list.php?pw=aq-q-0-1[/img]>

lingluoz 发表于 2008-6-23 22:10

在C语言的结构里面定义一个函数。。虽然C语言不像C++那样支持在结构里面定义函数。。但是你可以通过定义一个函数指针来实现。。如果有必要的话
在结构里面定义void (*pf_exit)(void);
调用的时候
(*stu.pf_exit)();
oh yeah你试试吧

cosdos 发表于 2008-6-23 22:56

#include <stdio.h>


struct class_t;
typedef struct class_t class_t;;

typedef struct data {
    int i;
    class_t * class;
} data;


struct class_t
{
    int (* print)(const char *, ...);
};

class_t funclass = {printf};

int main(void)
{

    data a;
    a.class = &funclass;
    a.i = 10;

    a.class->print("%d", a.i);
   
    getchar();
    return 0;
}

lingluoz 发表于 2008-6-24 08:31

LS解释一下代码好吗。。那个指针型函数的调用应该是(*pf)()这种形式的吧。。为什么可以直接调用呢。

sunkaidong 发表于 2008-6-24 09:05

#include <stdio.h>
struct class_t;
typedef struct class_t class_t;

typedef struct data {
    int i;
} data;
   
int (* print)(const char *, ...);

int _tmain(int argc, _TCHAR* argv[])
{

    data a;
    a.i = 10;
        print=printf;
    (*print)("%d\n", a.i);
    print("%d\n", a.i);
    getchar();
    return 0;
}
这两个都是对的

页: [1]

编程论坛