简体   繁体   中英

How to implement classes with references to each other?

I'm new to C++ programming, so maybe you'd find my question too stupid. Sorry about that, but I'd like to know how to implement this Java-style structure:

#include "B";
class A {
   B objB;
}
---
#include "A";
class B {
   A objA;
}

The compiler going crazy trying to understand this code. Could you please advise me about a possible solution? Thanks!

This code is illegal in C++ and the compiler is right to reject it. The problem is that if you have a concrete object of type A inside of an object of type B and vice-versa, then there is no meaningful definition of the size of either object. In particular, objects in C++ must each be at least one byte in size. Therefore, given an object of type A (call it a ), there must be one byte of storage for a , a.objB.objA , a.objB.objA.objB.objA , etc. In fact, you'd need infinite storage space, because there's always an object nested further inside of these objects!

To fix this, you'll want to change this so that you're storing pointers to objects of type B and A in A and B, respectively. This breaks the chain because while an A* pointer points to an A object, the pointer itself isn't an A object and thus uses only four bytes. Once you have this, you can use forward declarations to declare these pointers. For example:

File: Ah:

class B;
class A {
     B* objB;
};

File: Bh:

class A;
class B {
     A* objA;
};

Hope this helps!

You need to forward-declare

class B;

before you define class A, then continue as before. That would work for references, but not for objects like this, since you can't really have an object implicitly contain itself.

You cannot instantiate an object B inside an object A which itself is inside an object B . Recursively you would never be able to construct the object because it has infinite recursion.

What you can do:

#include "B"
class A {
    B *objB;
}

#include "A"
class B {
    A objA
}

Another way of seeing this is to consider a single source file, having included AH or BH "first". [ "first" being quoted given the likely confusion there as well.]

class A {
   B objB;
}
class B {
   A objA;
}

How can this make sense? We cannot possibly define A before we know B and we cannot define B before we know A. Hence the solution via indirection as noted by others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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