简体   繁体   English

在C中彼此定义结构

[英]Define structs in terms of each other in C

Is there a way to correctly define structs in a circular fashion (in C)? 有没有办法以循环方式(在C中)正确定义结构? In other words: 换一种说法:

//struct struct1;  Is this ok??

struct struct2 {

    struct struct1* someStruct1Var;
    //Other variables
};

struct struct1 {
   //Some variables
   struct2* (*someFunc)(struct2* someStruct2Var);
}

The behavior I basically want is that the first struct has a variable that is a pointer to an instance of the second (which is a global variable and only 1 will exist). 我基本上想要的行为是第一个结构体具有一个变量,该变量是第二个结构体实例的指针(这是全局变量,将仅存在1)。 Then I want the second struct to have function pointers that return the type of the first struct. 然后,我希望第二个结构具有返回第一个结构的类型的函数指针。 I want this behavior in order to implement basic object-oriented-like classes/objects. 我想要这种行为以便实现基本的面向对象的类/对象。 If there is a similar method that can accomplish the same thing, that would also be very helpful. 如果有类似的方法可以完成相同的事情,那也将非常有帮助。 Again, what I need is to have a class struct (struct1) containing function pointers that take as arguments and return variables the type of the object (struct2). 同样,我需要有一个包含函数指针的类struct(struct1),该函数指针将参数作为对象并返回对象(struct2)的类型。 Then, I need each object to have a reference to its global class variable (which is of type struct1). 然后,我需要每个对象都有对其全局类变量(类型为struct1)的引用。

Thank you! 谢谢!

You should forward declare your struct 您应该转发声明您的struct

typedef struct struct1 struct1;
typedef struct struct2 struct2;

struct struct2 {

    struct1* someStruct1Var;
    //Other variables
};

struct struct1 {
   //Some variables
   struct2* (*someFunc)(struct2* someStruct2Var);
}

Doing it with a typedef help to omit the struct keyword to name the type. 使用typedef帮助省略struct关键字来命名类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM