在c中的结构内声明变量

Declaring variables inside a struct in c

我想为我的编程语言制作一个面向对象的预处理器,它将我的语言转换为 C(如早期的 C++)。我想用结构模拟 类 。问题是:如何在这样的结构中声明一个变量:

typedef struct { //equivalent of class
   int a = 5;
   int (*sub)(int) = &int_sub; //function of a class, uses an external declared function
} class_name;

我试过上面的代码,但编译器是这样写的:

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token 
       void (*sub)(int) = &int_sub;

我有两个问题:

  1. 我可以在结构中声明一个变量吗?

  2. 如果是,怎么办?

您不能在结构定义中分配指针值。您可以使用一个函数来初始化它。

typedef struct { //equivalent of class
   int a;
   int (*sub)(int);
} class_name;

int int_sub (int a)
{
   // your stuff
   return 0;
}

int main()
{
   class_name myClassVariable;

   myClassVariable.a = 5;
   myClassVariable.sub = int_sub;

   printf("class_name.a = %d\n", myClassVariable.a );
   printf("class_name.sub = %p\n", myClassVariable.sub );
   printf("int_sub address = %p\n", int_sub );

   return 0;
}

或者,如 artm answer 所示,您可以初始化分配的变量:

class_name my_struct = { .a = 5, .sub = int_sub };

或者,您也可以初始化结构类型的变量。

int func( int a ){}

typedef struct {
    int a;
    int (*sub)(int);
} class_name;

class_name my_struct = { .a = 5, .sub = func };

我认为你的问题不是关于如何声明而是如何初始化结构成员。

在h文件中定义class为不透明类型。使用 typedef 作为函数指针。

h 文件

// opaque type declaration
typedef struct class_name class_name;

// types used by this class
typedef int sub_func_t (int);

// member functions of the class
class_name* class_init (int a, sub_func_t* sub);

然后从其构造函数中初始化它:

c文件

struct class_name { //equivalent of class
   int a;
   sub_func_t* sub;
};

class_name* class_init (int a, sub_func_t* sub) 
{ 
  class_name* new_class = malloc(sizeof(*new_class)); 
  assert(new_class != NULL);
  *new_class = (class_name){a, sub};
  return new_class; 
}