Skip to content

Instantly share code, notes, and snippets.

@owlfox
Created April 1, 2016 00:38
Show Gist options
  • Save owlfox/53196bc077d709477deb6f46f9ee02db to your computer and use it in GitHub Desktop.
Save owlfox/53196bc077d709477deb6f46f9ee02db to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
/* forward declaration */
typedef struct object Object;
typedef int (*func_t)(Object *);
struct object {
int a, b;
func_t add, sub;
};
static int add_impl(Object *self) { return self->a + self->b; }
static int sub_impl(Object *self) { return self->a - self->b; }
int init_object(Object **self)
{
if (NULL == (*self = malloc(sizeof(Object)))) return -1;
(*self)->a = 0; (*self)->b = 0;
(*self)->add = add_impl; (*self)->sub = sub_impl;
return 0;
}
int main(int argc, char *argv[])
{
Object *o = NULL;
init_object(&o);
o->a = 9922; o->b = 5566;
printf("add = %d, sub = %d\n", o->add(o), o->sub(o));
return 0;
}
@owlfox
Copy link
Author

owlfox commented Apr 1, 2016

OOP 是一種態度

@owlfox
Copy link
Author

owlfox commented Apr 1, 2016

http://ubuntuforums.org/archive/index.php/t-141536.html

int (*func_t)(int);

creates a variable named func_t that can hold an address of a function that takes one int as an argument and returns an int.

@owlfox
Copy link
Author

owlfox commented Apr 1, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment