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/

 

posted @ 2021-07-06 14:54  dong1  阅读(37)  评论(0编辑  收藏  举报