简体   繁体   English

向前声明同一类中的类型

[英]Forward declaration of types in the same class

I have a class with a few simple structs like this (simplified code) inside a class: 我在一个类中有一个带有一些简单结构的类(简化代码):

typedef struct  
{
    Struct2* str2;
}Struct1;

typedef struct  
{
    Struct3* str3;
    Struct1* str1;
}Struct2;

typedef struct  
{
    Struct1* str1;
    Struct2* str2;
    Struct3* str3;
}Struct3;

which, of course, gives me syntax errors. 当然,这给了我语法错误。 So I forward declared each one, but that does not work because then I have redefinitions. 因此,我转发了每个声明,但这不起作用,因为那时我有重新定义。 I want to avoid putting each structure in a separate file; 我想避免将每个结构放在单独的文件中; is that possible? 那可能吗?

Rather than declare each type as a typedef , use the struct keyword the same way you would a class. 不必将每个类型都声明为typedef ,而应像使用类一样使用struct关键字。 Then your definitions won't look like redefinitions of the forward declarations. 这样,您的定义就不会看起来像前向声明的重新定义。

struct Struct1;
struct Struct2;

struct Struct1
{
    Struct2* str2;
};  

Use forward declaration and define structs without using typedef , as: 使用前向声明并在不使用typedef情况下定义结构,如下所示:

struct Struct2; //forward declaration
struct Struct3; //forward declaration

struct Struct1
{
    Struct2* str2; //here Struct2 is known to be a struct (to be defined later though)
};

struct Struct2
{
    Struct3* str3; //here Struct3 is known to be a struct (to be defined later though)
    Struct1* str1;
};

struct Struct3
{
    Struct1* str1;
    Struct2* str2;
    Struct3* str3;
};

You can forward declare them like this: 您可以像这样向前声明它们:

typedef struct Struct1 Struct1;
typedef struct Struct2 Struct2;
typedef struct Struct3 Struct3;

And you resolve them thus: 然后您可以解决它们:

struct Struct2 { ... };

I used named structs, so this is valid C or C++. 我使用了命名结构,因此这是有效的C或C ++。 As Nawaz pointed out, you don't need the typedef at all in C++. 正如Nawaz所指出的那样,在C ++中根本不需要typedef。 In C++, the name of a struct automatically becomes a type, but in C it is not. 在C ++中,结构的名称自动成为类型,但在C中则不是。

Here is the whole unit: 这是整个单元:

#include <stdio.h>

typedef struct Struct1 Struct1;
typedef struct Struct2 Struct2;
typedef struct Struct3 Struct3;

struct Struct1  {
        Struct2* str2;
} ;

struct Struct2 {
        Struct3* str3;
        Struct1* str1;
} ;

struct Struct3  {
        Struct1* str1;
        Struct2* str2;
        Struct3* str3;
} ;

int main()
{
        printf("Size of Struct1: %d\n", sizeof(Struct1));
        printf("Size of Struct2: %d\n", sizeof(Struct2));
        printf("Size of Struct3: %d\n", sizeof(Struct3));
}

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

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