开发者

How to define two depend classes?

take a look at following simple code :

class A;
class B
{
    A a;
};

cl开发者_Go百科ass A
{
    B b;
};

int main(int argc, char *argv[])
{
    return 1;
}

it does not compile, why ?

Error Message from GCC (Qt): main.cpp:6: error: field ‘a’ has incomplete type


well that's impossible since A would contain a B which would contain an A etc. if they depend on eachother they could hold references or pointers to eachother or one could hold the other whilst the other holded a pointer/reference.


IIRC, if you define an object of some kind, it must be a complete type, otherwise its size wouldn't be known and the layout of the struct which would contain it couldn't be known.

Moreover the thing you wrote makes no sense, because if you wanted to create an object of type A, it would include an object of type B, which would contain an object of type A, and so on. Thus, an object of type A or of type B would take infinite space in memory, which is definitely not good.

Instead, if those members were pointers/references the forward declarations would suffice and you wouldn't even have this "little" problem of requiring infinite memory for a structure. :)


In order for the compiler to be able to build class B it needs to know the size of all its members. Forward declaration class A; does not tell that, only introduces the name A into the scope. You can use a pointer or a reference to A, the size of which compiler always knows.


You must make at least one of them a pointer. Otherwise, you are asking each instance to allocate an instance of the other class. In other words, you are asking it to allocate an infinte amount of memory:


you cannot have A a. You have forward declared A, you cannot use it until you define it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜