3 Pluspunkte 0 Minuspunkte
Kann ich so etwas wie eine Klasse in C erstellen? Also ein Objekt das Eigenschaften wie int, float, etc. aber auch Funktionen haben kann?
von  

2 Antworten

0 Pluspunkte 0 Minuspunkte

Es gibt keine Objekte oder Klassen in C. Du kannst eine Struktur erstellen, die Zeiger auf Funktionen enthält.

#include <stdio.h>
 
typedef struct {
    int num;
    void (*someMethod)(void);
} Test;
 
void hellofunction(void) {
    printf("hello");
}
 
void worldfunction(void) {
    printf("world");
}
 
int main(void) {
    Test test;
    test.num = 13;
    test.someMethod = hellofunction;
    test.someMethod();
    test.someMethod = worldfunction;
    test.someMethod();
}

von  
0 Pluspunkte 0 Minuspunkte

Es gibt keine Klassen in C. Du kannst eine Struktur erstellen und eine Funktion als Constuctor. Das ist zwar auch keine Klasse aber wäre eine Möglichkeit.

typedef struct Class Class;
 
struct Class {
    double width, height; /* Variables */
    double (*area)(Class *_class); /* Function pointer */
};
 
/* Function */
double calc(Class *_class) {
    return _class->width * _class->height;
}
 
/* Constructor */
Class _Class(int w, int h) {
    Class s;
    s.width = w;
    s.height = h;
    s.area = calc;
    return s;
}
 
int main() {
    Class s1 = _Class(2, 3);
 
    //s1.width = 4;
    //s1.height = 5;
 
    printf("width = %f\n", s1.width);
    printf("height = %f\n", s1.height);
    printf("area = %f\n", s1.area(&s1));
 
};

von (716 Punkte)