Declaring variables inside a struct in c [duplicate]

不羁岁月 提交于 2019-12-14 00:09:54

问题


I wanted to make an object oriented preprocessor to my programming language which converts my language into C (like early C++). And I want to simulate the classes with structures. And the question is: how can I declare a variable inside a struct like this:

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

I tried the code above but the compiler wrote this:

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

I have two questions:

  1. Can I declare a variable inside a struct?

  2. If yes, how?


回答1:


Alternatively, you can also initialize the variable of your struct type.

int func( int a ){}

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

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



回答2:


You can't assign a pointer value inside a struct definition. You could use a function to init it.

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;
}

Or, as shown in artm answer, you could init your allocated variable:

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



回答3:


I take it your question is not about how to declare but how to initialize a structure member.

Define the class as opaque type in the h file. Use typedef for function pointers.

h file

// 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);

Then initialize it from inside its constructor:

c file

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; 
}


来源:https://stackoverflow.com/questions/35126941/declaring-variables-inside-a-struct-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!