- #import "Dog.h"
- #import "Person.h"
- #import <Foundation/Foundation.h>
- int sum(int x, int y) {
- return x + y;
- }
- int (*func3)(int, int);
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- Person * p = [[Person alloc] init];
- Dog * dog = [[Dog alloc] init];
- SEL s1 = NSSelectorFromString(@"run"); //人的方法
- SEL s2 = NSSelectorFromString(@"eat"); //狗的方法
- IMP imp1 = [p methodForSelector:s1]; //<---使用p对象找到函数地址.
- IMP imp2 = [dog methodForSelector:s2];
- void (*func1)(id, SEL) = (void *)imp1; // <---这个才是函数指针
- void (*func2)(id, SEL) = (void *)imp2;
- func1(dog, s1); //即便是狗也能调用 人的方法...
- func2(p, s2); //参数是 id,SEL
- //
- func3 = sum;
- int result = func3(2, 3);
- printf("%d\n", result);
- }
- return 0;
- }
复制代码 |