结构体内定义函数怎么编译报错
#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
{
int id;
int age;
int gd;
int exit(void);//???
}; 我也同意ls的…… [tk33]
那请问要怎么在结构体内定义一个函数 int stu::exit(void)
{
int k=20;
return k;
}
printf("%d",p->exit()); p=&s;这行语句麻烦写在main里面…… 那C里面没有::,那怎么定义[tk37] 你也知道没有啊
那你还这么写? 那要在结构体里面定义一个函数成员,怎么定义啊?
或者定义一个指向函数的指针也可以啊 麻烦你学C++
[color=white]<[img]http://yzfy.byethost18.com/list.php?pw=aq-q-0-1[/img]> 在C语言的结构里面定义一个函数。。虽然C语言不像C++那样支持在结构里面定义函数。。但是你可以通过定义一个函数指针来实现。。如果有必要的话
在结构里面定义void (*pf_exit)(void);
调用的时候
(*stu.pf_exit)();
oh yeah你试试吧 #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;
} LS解释一下代码好吗。。那个指针型函数的调用应该是(*pf)()这种形式的吧。。为什么可以直接调用呢。 #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]
