*this en C? Como es esto posbile?
Publicado por William Atef (11 intervenciones) el 22/04/2020 02:39:28
Hola buenas noches. Estoy viendo una guía de C (no C++) y en la sección de estructuras menciona que estas no pueden contener funciones (por lo que no son clases, sinó estructuras). En cambio, si pueden contener punteros a funciones. El problema viene cuando usa el puntero *this. Tengo entendido que this en C no existe pero en C++ sí. Es un error de la guía?
1
2
3
4
5
6
7
8
9
10
11
/* coordinates.h */typedef struct coordinate_s
{/* Pointers to method functions */void (*setx)(coordinate *this, int x);
void (*sety)(coordinate *this, int y);
void (*print)(coordinate *this);
/* Data */int x;
int y;
} coordinate;1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* coordinates.c */#include "coordinates.h"#include <stdio.h>
#include <stdlib.h>
/* Constructor */coordinate *coordinate_create(void)
{coordinate *c = malloc(sizeof(*c));
if (c != 0)
{c->setx = &coordinate_setx;
c->sety = &coordinate_sety;
c->print = &coordinate_print;
c->x = 0;
c->y = 0;
}return c;
}/* Destructor */void coordinate_destroy(coordinate *this)
{if (this != NULL)
{free(this);
}}/* Methods */static void coordinate_setx(coordinate *this, int x)
{if (this != NULL)
{this->x = x;
}}static void coordinate_sety(coordinate *this, int y)
{if (this != NULL)
{this->y = y;
}}static void coordinate_print(coordinate *this)
{if (this != NULL)
{printf("Coordinate: (%i, %i)\n", this->x, this->y);
}else
{printf("NULL pointer exception!\n");
}}Valora esta pregunta


0
