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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章