问题描述
有一个 Square
指向四个 Face
。每个 Face
指向两个 Square
。因为其中一个类首先被定义,编译器会抱怨。那么我该如何解决这个问题呢?使用指针的目的是,如果我在一个脸改变,我不需要对正方形做任何改变。
There is a Square
which points to four Face
s. Also each Face
points to two Square
s. 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]
};
推荐答案
向前声明一个类;
class Face;
class Square{
Face* faces[4];
};
class Face{
Square* squares[2]
};
注意:通过转发声明,您只能使用指针/参考(正如您现在使用的)。但是你不能在 Square
中使用 Face faces [4];
。因为它是一个声明,而不是定义。要使用对象,编译器必须知道对象的定义。
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.
这篇关于其成员指向彼此的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!