Micro class system in C

Asked

Viewed 77 times

2

What I would like is to automatically initialize a struct that receives function pointers. For example:

struct teste{
    int x;
    int y;
    int (*soma)(int, int);
};

typedef struct teste Teste;

int soma(int a, int b){
    return a + b;
}

Teste *t1;
t1->soma = soma;

printf("---> 2 + 2 = %d \n", t1->soma(2, 2)); // ---> 2 + 2 = 4

This compiles and performs very well. However, I would like to not need to do the:

Teste *t1;
t1->soma = soma;

And just do something like:

Teste *t1;
*t1 = newTeste();

Or even:

Teste *t1 = newTeste();

Where the function newTeste() would be something like:

Teste newTeste(){
    Teste *t;
    t->soma = soma;
    return *t;
}

That compiles but does not wheel.

I know I’m getting lost in pointers, but I can’t see exactly where. I also don’t know if what I want to do is something viable, I just came up with this idea of micro simulate a class and I would like to put into practice.

3 answers

2


If you are returning a pointer the type of function must be a pointer, only this is missing.

Teste *newTeste() {
    Teste *t;
    t->soma = soma;
    return *t;
}

I put in the Github for future reference.

There is another problem, this variable soma seems magical, should probably be global, should not do this, especially when you want to simulate a class.

There are other conceptual errors in this construction.

0

Teste newTeste(){
    Teste *t;
    t->soma = soma;
    return t;
}

Try this way, without the * in Return.

0

Thank you so much for your help. I ended up mixing some of the ideas presented and I arrived at the following code that meets what I wanted so far:

Declaration of "micro class":

typedef struct teste{
    int x;
    int y;
    int (*soma)(int, int);
    int (*subtrai)(int, int);
    int (*divide)(int, int);
} Teste;

Teste newTeste(){
    int soma(int a, int b){
        return a + b;
    }

    int subtrai(int a, int b){
        return a - b;
    }

    int divide(int a, int b){
        return a / b;
    }

    Teste t;
    t.soma = soma;
    t.subtrai = subtrai;
    t.divide = divide;
    return t;
};

Utilizing:

Teste t1 = newTeste();
t1.x = 12;
t1.y = 7;

Teste t2 = newTeste();
t2.x = 5;
t2.y = 5;

Teste t3 = newTeste();
t3.x = 4;
t3.y = 4;

// ---> 12 + 7 = 19
printf("---> %d + %d = %d \n", t1.x, t1.y, t1.soma(t1.x,t1.y)); 
// ---> 5 - 5 = 19
printf("---> %d - %d = %d \n", t2.x, t2.y, t2.subtrai(t2.x,t2.y)); 
// ---> 4 / 4 = 4
printf("---> %d / %d = %d \n", t3.x, t3.y, t3.divide(t3.x,t3.y)); 

As suggested, I have created a scope for declaring "methods" Now I go in search of a "this".

Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.