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
", __FUNCTION__, xobj->x); }
void func2(struct X *xobj) { printf("%s, %d
", __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/

原文地址:https://www.cnblogs.com/dong1/p/14976967.html