其成员指向彼此的类 [英] Classes whose members pointing to each other

查看:120
本文介绍了其成员指向彼此的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个 Square 指向四个 Face 。每个 Face 指向两个 Square 。因为其中一个类首先被定义,编译器会抱怨。那么我该如何解决这个问题呢?使用指针的目的是,如果我在一个脸改变,我不需要对正方形做任何改变。

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]
};


推荐答案

向前声明一个类;

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.

这篇关于其成员指向彼此的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆