Created
April 1, 2016 00:38
-
-
Save owlfox/53196bc077d709477deb6f46f9ee02db to your computer and use it in GitHub Desktop.
Object-Oriented Programming in C, src: https://embedded2015.hackpad.com/Object-Oriented-Programming-in-C-Xz4AOssZPCj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OOP 是一種態度