Re: obj function hello()
- From: Ian Collins <ian-news@xxxxxxxxxxx>
- Date: Fri, 09 Feb 2007 14:41:58 +1300
gert wrote:
On Feb 9, 1:30 am, Ian Collins <ian-n...@xxxxxxxxxxx> wrote:No, you are still assuming C is an OO language. In C you have to be
You can't have functions in structs in C. What yo can have is function
pointers:
struct Obj {
int someInt;
int (*someFn)(void);
};
But you have to assign a function address to the pointer for each
instance of Obj.
So this means i have to do something like this then ?
#include <stdio.h>
struct obj {
char *data = ''
int (*add)(void);
}
explicit:
#include <stdio.h>
#include <stdlib.h>
typedef struct Obj {
int value;
int (*add)(struct Obj*,int);
} Obj;
int add( Obj* obj, int val ) {
obj->value += val;
return obj->value;
}
int main(void) {
Obj* obj = malloc( sizeof obj );
obj->value = 0;
obj->add = add;
obj->add( obj, 42 );
printf( "%d\n", obj->value );
return 0;
}
--
Ian Collins.
.
- Follow-Ups:
- Re: obj function hello()
- From: gert
- Re: obj function hello()
- From: Ian Collins
- Re: obj function hello()
- References:
- obj function hello()
- From: gert
- Re: obj function hello()
- From: Ian Collins
- Re: obj function hello()
- From: gert
- Re: obj function hello()
- From: Ian Collins
- Re: obj function hello()
- From: gert
- obj function hello()
- Prev by Date: Re: IS this a proper way of freeing memory with free()
- Next by Date: Re: obj function hello()
- Previous by thread: Re: obj function hello()
- Next by thread: Re: obj function hello()
- Index(es):
Relevant Pages
|