我试图使用C以面向对象的方式进行编码。我的目标是从基类“ Shape”派生“ Square”类。但是我收到一条错误消息“常量表达式中不允许函数调用”。为什么我会收到此消息以及如何解决此问题?
我正在关注本文https://www.codementor.io/michaelsafyan/object-oriented-programming-in-c-du1081gw2
//shape.h
//Some code
typedef struct ShapeType{
int buffer_size;
const char* (*name)(Shape*);
int (*sides)(Shape*);
void (*destroy)(Shape*);
} ShapeType;
ShapeType* ShapeType_create(
int buffer_size,
const char* (*name)(Shape*),
int (*sides)(Shape*),
void (*destroy)(Shape*)
);
//Some code
//square.c
typedef struct SquareData{
int x;
int y;
int width;
int height;
} SquareData;
//...
const char* square_name(Shape * self)
{
return "Square";
}
int square_sides(Shape * self)
{
return 4;
}
void* square_destroy(Shape * square)
{
free(square);
}
static ShapeType* square_type =
ShapeType_create(
sizeof(SquareData),
&square_name,
&square_sides,
&square_destroy
); //error in this line
//...