可以两个类使用C ++看到对方? [英] can two classes see each other using C++?

查看:121
本文介绍了可以两个类使用C ++看到对方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个类A,在那里我想调用一些类B的功能。所以我包括b.h。但是,在B类中,我想调用A类函数。如果我包括a.h,它最终在一个无限循环,对吧?

解决方案

每个类(A和B)都应该有一个头文件和一个实现文件。 / p>

每个头文件(例如 Ah )不应包含其他头文件(例如 Bh ),但可以包括对另一个类的前向引用(例如 B类; ),然后可以使用指针和/在其声明中的另一个类(例如 A类可能包含作为数据成员的 B * 每个CPP文件(例如 A.cpp )可以包括多于一个的头文件(例如,一个方法参数)。



<例如 Ah Bh )。建议每个CPP文件首先包含自己的头文件(例如 A.cpp 应该包括 Ah code> Bh ,而 B.cpp 应包括 Bh code> Ah )。



每个头文件应该只包含声明,而不是类的定义:将列出类方法的签名,而不是方法体/实现(方法体/实现将在 .cpp 文件中,而不是在头文件中) 。因为头文件不包含实现细节,所以它们不依赖于(不需要看到)其他类的细节;最多他们需要知道,例如 B 是类的名称:它可以从转发声明中获得,而不是通过在另一个头文件中包含头文件头文件。


So I have a class A, where I want to call some class B functions. So I include "b.h". But, in class B, I want to call a class A function. If I include "a.h", it ends up in an infinite loop, right? What can I do about it?

解决方案

Each class (A and B) should have a header file and an implementation file.

Each header file (e.g. A.h) should not include the other header file (e.g. B.h) but may include a forward reference to the other class (e.g. a statement like class B;), and may then use pointers and/or references to the other class in its declaration (e.g. class A may contain a B* as a data member and/or as a method parameter).

Each CPP file (e.g. A.cpp) may include more than one header file (e.g. A.h and B.h). It's recommended that each CPP file should include its own header file first (e.g. A.cpp should include A.h and then B.h, whereas B.cpp should include B.h and then A.h).

Each header file should contain only the declaration, and not the definition of the class: for example it will list the signatures of the class' methods, but not the method bodies/implementations (the method bodies/implementations will be in the .cpp file, not in the header file). Because the header files don't contain implemention details, they therefore don't depend on (don't need to see) details of other classes; at most they need to know that, for example, B is the name of a class: which it can get from a forward declaratin, instead of by including a header file in another header file.

这篇关于可以两个类使用C ++看到对方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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