开发者

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;
    St开发者_如何学Cruct1* 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. 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:

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++. As Nawaz pointed out, you don't need the typedef at all in C++. In C++, the name of a struct automatically becomes a type, but in C it is not.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜