[Linuxtrent] Re: [OT] C: this

  • From: neugens <neugens@xxxxxxxxx>
  • To: linuxtrent@xxxxxxxxxxxxx
  • Date: 21 May 2002 19:42:53 +0200

Il mar, 2002-05-21 alle 18:54, Lo'oRiS il Kabukimono ha scritto:
 
> Esiste in C qualcosa tipo il "this"?

Si, con le callback appunto, faccio un esempio, definiamo tre files:

1 - nano.h, header per esportare l'interfaccia
2 - nano.c, implementa l'interfaccia
3 - main.c, usa l'interfaccia nano


in nano.h:

typedef struct __nano nanoT {
        
        int x_position, y_position;
        
        /* methods */
        void (*move_left) (nanoT * this);
        void (*move_right) (nanoT * this);

};

/* constructor */
nanoT *new_nanoT(int x_position, int  y_position);

=============================================

in nano.c:

static void move_left (nanoT *this_nano);
static void move_right (nanoT *this_nano);

/* constructor */
nanoT* new_nanoT (int x_position, int  y_position)
{
        nanoT *this;
        
        /* allocate memory */
        this = malloc (sizeof (nanoT));

        /* init data */
        this->x_position = x_position;
        this->y_position = y_position;
                        
        /* sets the member functions */
        this->move_left = move_left;
        this->move_right = move_right;

        return (nanoT *) this;
        
} // new_nanoT

/* methods */
static void move_left (nanoT *this)
{       
        /* checks for movements */
        fprintf (stderr, "moving left\n");
        fprintf (stderr, "old position: %d\n", this->x_position);
        
        /* moves */
        this->x_position = this->x_position + 1;

        /* checks again */
        fprintf (stderr, "new position: %d\n", this->x_position);
        
}                        // move_left

static void move_right (nanoT *this)
{
        /* same as above... replace + 1 with -1 */      
}                        // move_right


===================================================

in main.c:

int main(int argc, char **argv)
{
        nanoT *nano;

        nanoT = new_nanoT(0, 0);

        nanoT->move_left(nanoT);
        nanoT->move_left(nanoT);
        nanoT->move_right(nanoT);

        exit(0);
}


E' un esempio rapido, ovviamente dovresti anche inserire un distruttore,
stare attento agli oggetti allocati, e separare meglio implementazione e
definizoni. Tuttavia dovrebbe rendere l'idea.

Mario
-- 
Please avoid sending me Word or PowerPoint attachments.
See http://www.fsf.org/philosophy/no-word-attachments.html

-- 
Per iscriversi  (o disiscriversi), basta spedire un  messaggio con SOGGETTO
"subscribe" (o "unsubscribe") a mailto:linuxtrent-request@xxxxxxxxxxxxxxxxx


Other related posts: