在需要时处理循环依赖关系 [英] Dealing with cyclic dependencies when you need them

查看:86
本文介绍了在需要时处理循环依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





通过阅读这个问题的标题,你已经知道我正在处理什么,这并不好玩。



我有大约20个课程,其中一些与其他相关的课程有关。例如,

Hi,

You already know what I'm dealing with by reading the title of this question and it's not fun.

I have about 20 classes, where some relate to others which relate back. For example,

AEntity* InventoryItem::ToEntity();
InventoryItem* AEntity::ToItem();





我发现通过注释掉所有代码循环中的一个文件的cpp,并在.h中注释掉它的包含,错误消失了。由于这个问题,我得到了大约90个不相关的错误。我不会在这里列出它们,但它的内容如下:



•xxx不是'yyy'的成员

•缺失类型说明符 - 假设int(我在那里清楚地显示类型)

•语法错误:在'*'之前缺少';' - 单击错误显示完美的代码,感谢intellisense

•前面的预期令牌';'



我甚至尝试将循环中的一个包含移动到该文件的cpp而不是。 h,它的工作原理。与其他人一起,它没有,那些错误仍然存​​在。另外,我鄙视在.hpp中包含一些内容和在.cpp中包含一些内容的想法,这很麻烦。



处理此问题的最佳方法是什么? />


我尝试了什么:



所有已经提到过的东西。



I've found that by commenting out all of the code in the cpp of one file in the loop, and commenting out its includes in the .h, the errors go away. I get around 90 irrelevant errors due to this problem. I won't list them here, but it's things such as:

• xxx is not a member of 'yyy'
• missing type specifier - int assumed (where I have the type clearly there)
• syntax error: missing ';' before '*' - clicking on the error shows perfectly fine code, thanks intellisense
• expected token(s) preceding ';'

I've even tried moving one of the includes in the loop to that file's cpp instead of .h, and it works. With others, it doesn't, and those errors are still there. Also I despise the idea of having some includes in the .h and some in the .cpp, that's messy.

What's the best way to deal with this?

What I have tried:

Everything already mentioned in question.

推荐答案

循环依赖是一个非常明确的标志,代码需要一些重新设计和重新架构。当它是一个更大或更长时间运行的项目时,我真的会花时间重新设计类。所有其他东西都是修复,你将永远有糟糕的代码质量,你可能会遇到麻烦。这是非常糟糕的,当它是一些家庭作业或专业软件。



常见的解决方法是前向声明或接口。您还可以使用void指针作为函数参数,而不是在实现中强制转换。或者取决于使用消息或回调的操作系统。我使用了一些平面接口,其中复杂对象的所有参数都作为普通数据传输。



最好是拿一张空白纸一杯你最喜欢的饮料和零食,从头开始。
Cyclic dependencies are a very clear sign that the code needs some redesign and re-architecture. When it is a greater or longer running project I really would take the time and redesign the classes. All other stuff are "fixes" and you will have bad code quality forever and you may run into trouble in the future. That is very bad, when it is some homework or professional software.

Common workarounds are forward declarations or interfaces. You can also use void pointers as function arguments and than cast in the implementation. Or depending on the OS working with messages or callbacks. I have used some "flat interfaces" in which all arguments of a complex object are transfered as plain data.

Best is to take a empty sheet of paper a cup of your favorite drink and a snack and start from the scratch.


这篇关于在需要时处理循环依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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