OO With Function Pointers

Hareesh Nagarajan (hnagaraj AT cs uic edu)
Mon Nov 21 00:58:19 CST 2005

This document may never be updated

#include <stdio.h>
struct X {
	int x;
	void (*fp)(struct X *);
};

void func1(struct X *xobj) { printf("%s, %d\n", __FUNCTION__, xobj->x); }
void func2(struct X *xobj) { printf("%s, %d\n", __FUNCTION__, xobj->x); }

main() {
	struct X obj;
	obj.x  = 10;
	obj.fp = func1;
	obj.fp(&obj);
	obj.x  = 20;
	obj.fp = func2;
	obj.fp(&obj);
}

Output

$ ./a.out
func1, 10
func2, 20

Cool eh?

 

copyright

https://www2.cs.uic.edu/~hnagaraj/articles/function-pointers/

 

上一篇:37.第六章 Shell脚本编程高级进阶(二)


下一篇:Java Synchronized实现互斥之应用与源码初探