本文介绍了前向声明和命名空间(c ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我的问题:有两个类,A类和B类,所以我得到A.h和A.cpp和B.h和B.cpp。 A需要知道B和B需要知道A.我解决了以下方式(我不知道为什么它必须这样...)Got two classes, class A and B, so i got A.h and A.cpp and B.h and B.cpp.A needs to know B and B needs to know A. I solved it the following way (i don't know why it has to be so...) Ah:#include "B.h"class A{ ... A.cpp:#include "A.h" Bh:#include "A.h"class A; // forward declarationclass B { ... B.cpp:#include "B.h"我使用一个正向声明,它工作。I used one forward declaration and it works.问题是,两个类都需要在命名空间ui。或者至少我认为这是意义:The Problem is, that both classes need to be in the namespace "ui". Or at least I think this is the meaning: Ah:#include "B.h"namespace ui{ class A;}class A{ ...B.h:#include "A.h"namespace ui{ class B;}class B{ ...不再工作了。我现在必须做什么,以使它再次使用命名空间和转发声明?This doesn't work anymore. What do I have to do now to make it work again with namespace and forward declaration?这两个都必须在这个命名空间。我正在使用Qt和行namespace ui {等等是需要的。和两个类需要相互了解。 我已经尝试过这样做:Both have to be in this namespace. I'm working with Qt and the lines "namespace ui{" etc. are needed. And both classes need to know each other.I already tried just to make this:namespace ui{ class A; class B;},但这不起作用...in both headers, but this doesn't work... Btw:所有Header-Files也有ifndef机制。Btw: All Header-Files also got the "ifndef"-mechanism.推荐答案 p>如果我理解你的权利,你用这样的结构声明2种不同的类型:If I understand you right, you declare 2 different types with such a construct:#include "B.h"namespace ui{ class A;}class A{ ... };在这里你指出有一个 A类在命名空间 ui 中,但在全局命名空间中定义类A 。因此, ui :: A 已声明,但永远不会定义。将 A 的定义也移动到 ui 命名空间:Here you state that there is a class A in the namespace ui, but you define a class A in the global namespace. Therefore ui::A is declared but never defined. Move the definition of A to the ui namespace as well:#include "B.h"namespace ui{ class A;}//somewhere later:namespace ui{ class A{ ... };} 这篇关于前向声明和命名空间(c ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
05-27 22:27
查看更多