当前位置:   article > 正文

原来C语言也可以面向对象(一)_c语言代码可以具备面向对象的风格吗

c语言代码可以具备面向对象的风格吗

C语言是一门博大精深的语言,我相信没有研读过Linux中代码的人,很少有人体会到吧,废话不多说,简单的写了一个测试demo


test.h

  1. typedef void (* func1_callback)(void);
  2. typedef void (* func2_callback)(int i);
  3. typedef struct {
  4. int size;
  5. func1_callback func1_cb;
  6. func2_callback func2_cb;
  7. } testCallback;
  8. typedef struct {
  9. int size;
  10. int (*init)(testCallback *_tcb);
  11. int (*set)(int i);
  12. int (*release)(void);
  13. } testInterface;

test.c

  1. #include "test.h"
  2. #include <stdio.h>
  3. testCallback tcb;
  4. int test_init(testCallback *_tcb) {
  5. printf("This is test init function.\n");
  6. tcb = *_tcb;
  7. tcb.func1_cb();
  8. return 0;
  9. }
  10. int test_set(int i) {
  11. printf("This is test set function, argumaent i is : %d\n", i);
  12. tcb.func2_cb(i);
  13. return 0;
  14. }
  15. int test_release(void) {
  16. printf("This is test release function.\n");
  17. return 0;
  18. }
  19. static const testInterface tInterface = {
  20. .size = sizeof(testInterface),
  21. .init = test_init,
  22. .set = test_set,
  23. .release = test_release,
  24. };
  25. const testInterface *get_test_interface() {
  26. return &tInterface;
  27. }

main.c

  1. #include "test.h"
  2. #include <stdio.h>
  3. void func1_cb() {
  4. printf("This is func1 cb, has no argument.\n");
  5. }
  6. void func2_cb(int i) {
  7. printf("This is func2 cb, argument i is : %d\n", i);
  8. }
  9. testCallback tcb = {
  10. sizeof(testCallback),
  11. func1_cb,
  12. func2_cb,
  13. };
  14. static const testInterface *ti;
  15. int main(void) {
  16. ti = get_test_interface();
  17. ti->init(&tcb);
  18. ti->set(10);
  19. ti->release();
  20. return 0;
  21. }

这个测试demo很简单,不用解释了吧,这篇先这样了。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43374
推荐阅读
相关标签
  

闽ICP备14008679号