可以两个类使用C ++看到对方?

编程入门 行业动态 更新时间:2024-10-24 09:19:54
本文介绍了可以两个类使用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 ++看到对方?

本文发布于:2023-05-25 19:38:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/320911.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!