Micro system of classes in C

1

Hello. I have a small problem that I can not resolve.

What I would like to do is simply initialize a struct that receives function pointers automatically. 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 not want to do the following:

Teste *t1;
t1->soma = soma;

And just do something like:

Teste *t1;
*t1 = newTeste();

Or even:

Teste *t1 = newTeste();

Since the newTeste () function would look something like:

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

This compiles but does not spin.

I know I'm getting lost in pointers, but I can not see exactly where. I also do not 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 it into practice.

Thanks in advance.

    
asked by anonymous 25.05.2018 / 00:26

3 answers

1

If a pointer is returning, the function type must be a pointer, that's all it needs.

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

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

There are other conceptual errors in this construction.

    
25.05.2018 / 00:31
0
Teste newTeste(){
    Teste *t;
    t->soma = soma;
    return t;
}

Try like this, without the * no return.

    
25.05.2018 / 00:32
0

Thank you for the help. I ended up mixing a bit of the ideas presented and I came up with the following code that meets what I wanted so far:

Micro-class declaration:

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;
};

Usage:

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 created a scope for the declaration of "methods" Now I'm looking for a "this".

Thank you very much.

    
25.05.2018 / 04:34