2011-05-09 95 views
1

我最近刚换了从Java编程的C/C++编程所以请原谅我,如果这是一个愚蠢的问题:结构的C/C++

我有它由一个结构,其中包括2的头文件来自不同位置的另一个头文件的结构。它看起来是这样的:

struct A { 
    struct B variable1; 
    struct C *variable2; 
    ... more variable declarations here. 
}; 

其中包含结构B和结构C中声明的头文件不包含在这个特定的头文件,但即便我做了包括他们并没有区别 - 在这两种情况下编译时我得到

error: field 'variable1' has incomplete type 

我只是想知道如果有人知道这可能是从什么? 谢谢!

+2

请显示'struct B'的定义代码... – 2011-05-09 15:43:00

+0

确保'struct B'或'struct C'声明中没有包含任何宏,这使得它们在'struct A中不可见'。 – yasouser 2011-05-09 15:47:44

+0

你确定你在struct A之前声明了struct B和struct C吗? – ascanio 2011-05-09 15:49:00

回答

4

如果您不包括struct B的定义,您应该会看到提到的错误,因为结构的大小尚未知。的struct C的类型,你只能有一个指针可能只是预先宣布:

struct C; 

如果您有与struct B定义的文件,你不应该得到的错误,所以如果你仍然这样做指向你的代码中的其他错误。

-3

尝试向前声明:

struct B; 
struct C; 
struct A { 
    struct B variable1; 
    struct C *variable2; 
    ... more variable declarations here. 
}; 
+3

-1:此处的'struct B'的前向声明是不够的。 – 2011-05-09 15:46:50

1

也可能是结构定义的顺序? 工作

struct b { 
    int y; 
}; 

struct a { 
    int x; 
    struct b c; 
}; 

同样的错误你:结构,B就不需要结构A.

我的测试是之前定义,并准备

struct a { 
    int x; 
    struct b c; 
}; 

struct b { 
    int y; 
}; 
0

结构一个在这里被定义,它必须有一个已知的大小。编译器必须知道什么是结构乙的大小来计算的规模结构体的成员,所以如果结构乙还没有定义,你将无法在使用它结构一个

你不必与结构C *这个问题,因为一个结构既保留了一个指向结构ç和指针的大小是已知的编译器。但是,你需要使用前声明它,如果它没有前结构定义的

struct B { 
    int b; 
} 
struct C; 
struct A { 
    struct B variable1; // valid 
    struct C *variable2; // valid 
    struct D variable3; // invalid 
    struct D* variable4; // invalid 
}; 

struct C { 
    int c; 
} 

struct D { 
    int d; 
} 
1

要声明的struct B一个实例中,struct B的定义必须是完整。幽州

其中包含结构B和结构C中声明的头文件不包含在这个头文件

此时编译器不知道是什么struct B样子,所以类型是不完整;因此它将拒绝任何试图创建实例struct B的声明,例如variable1的声明。您可以可以声明一个指向不完整类型的指针,就像您使用variable2一样,因为结构指针类型都具有相同的大小和表示。

然后你说出

,但就算我有他们这都没有区别

强烈建议(对我来说,反正)struct Astruct B之间循环依赖,这是坏朱朱。 struct A不能完成,直到struct B完成,并且struct B不能完成,直到struct A完成。将variable1更改为struct B的指针应该足以打破该依赖关系。

如果是这样,您可能需要重新访问您的设计。