Classes whose members pointing to each other [dupl

2019-09-08 10:56发布

问题:

This question already has an answer here:

  • C++ class forward declaration 8 answers

There is a Square which points to four Faces. Also each Face points to two Squares. Since one of the classes is defined first, compiler will complain. So how can I solve this problem? The aim of using pointers is that if I make a change in a face I will not need to make any changes for squares. In that case, this will be done automatically.

class Square
{
    Face* faces[4];
};

class Face
{
    Square* squares[2]
};

回答1:

Just forward declare one class;

class Face;
class Square{
 Face* faces[4];
};

class Face{
 Square* squares[2]
};

Note: by forward declaration, you can only use pointer/reference (as you are using now). But you can not use like Face faces[4]; in Square. Because it is a declaration, not definition. To use an object, compiler must know the definition of the object.