以下為一個引子: 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是用函數指針來模擬成員函數的。 Linux的源代碼中C語言對象化 參考Linux內核的源代碼中,有更好的使用
#include<stdio.h>
struct MyClass
{
char* name;
int age;
void (*funnull) ();
void (*func) (struct MyClass mc);
};
void realfunnull()
{
printf("hello world!\n");
}
void realfunc(struct MyClass mc)
{
printf("MyClass's name is:%s\n",mc.name);
printf("MyClass's age is:%d\n",mc.age);
}
int main()
{
struct MyClass mc = {"Simon", 25, realfunnull, realfunc};
mc.funnull();
mc.func(mc);
return 0;
}