我不得不使用C进行竞争,我需要模拟类。我试图构造一个简单的“point”类,它可以返回并设置点的X和Y坐标。然而,下面的代码返回错误,如“未知类型名称点”,“预期的标识符或(“和“预期的参数声明符”。这些错误是什么意思?我该如何纠正它们?这是编写“伪类”的正确方法吗?
typedef struct object object, *setCoordinates;
struct object {
float x, y;
void (*setCoordinates)(object *self, float x, float y);
void (*getYCoordinate)(object *self);
void (*getXCoordinate)(object *self);
};
void object_setCoordinates(object *self, float x, float y){
self->x = x;
self->y = y;
}
float object_getXCoordinate(object *self){
return self->x;
}
float object_getYCoordinate(object *self){
return self->y;
}
object point;
point.setCoordinates = object_setCoordinates;
point.getYCoordinate = object_getYCoordinate;
point.getXCoordinate = object_getXCoordinate;
point.setCoordinates(&point, 1, 2);
printf("Coordinates: X Coordinate: %f, Y Coordinate: %f", point.getXCoordinate, point.getYCoordinate);
参考:1. C - function inside struct 2. How do you implement a class in C?
5条答案
按热度按时间1yjd4xko1#
你会做得更好,以实现它如下:
需要注意的几点:
point
'thing'上调用一组point_*()
函数。printf()
调用中,您使用了point.getXCoordinate
-也就是说,您获取了它的地址并要求printf()
将其显示为float
许多库/API提供不透明的数据库。这意味着你可以得到一个“处理”的“东西".但你不知道“东西”里储存了什么然后,该库为您提供访问函数,如下所示。我建议你这样处理。
别忘了释放内存!
我在下面实现了一个例子。
point.h
point.c
main.c
edqdpe6u2#
你的代码有一些小错误。这就是为什么它不编译。
固定在这里:
至于方法,当你可以直接调用它们时,可能不需要在结构体中存储指向方法的指针:
ct3nt3jp3#
我也有一个C中的基本类仿真的例子[为特定应用程序指定的OP,尽管,这个答案是针对一般问题的]:
一个名为“c_class. h”的头文件
名为“c_class. c”的源代码文件
hsgswve44#
编写需要多态性的伪类的另一种方法是,创建一个单一的虚函数表,并让构造函数或工厂函数设置它。这里有一个假设的例子。(**编辑:**现在是MCVE,但对于真实的代码,重构为头文件和单独的源文件。)
这利用了结构的公共初始子序列可以通过指向它们中任何一个的指针来寻址的保证,并且每个示例只存储一个类开销指针,而不是每个虚函数一个函数指针。您可以使用虚拟表作为变体结构的类标识符。此外,虚拟表不能包含垃圾。虚函数调用需要解引用两个指针而不是一个,但是任何正在使用的类的虚表都极有可能在该高速缓存中。
我也注意到这个界面非常的 backbone 化;拥有一个除了转换回笛卡尔坐标之外什么也不能做极坐标类是愚蠢的,任何这样的实现至少需要某种方法来初始化动态内存。
如果你不需要多态性,请看Attie的更简单的答案。
dgsult0t5#
是的,你可以使用c struct创建一个“python类”,
下面是我如何实现python float built_in类型:
它将打印出3.2和5。